function setDataSource() in the AppModel - cakephp-2.0

I use this syntax in the AppModel
public function __construct($id = false, $table = null, $ds = null)
{
parent::__construct($id, $table, $ds);
$this->setDataSource('new_db');
}
The problem is that when this function is called,
Database Error
Error: SQLSTATE[42P01]: Undefined table: 7 ERROR:
missing FROM-clause entry for table "Aco" LINE 1: ...AND "Permission"."aco_id" IN (3, 2, 1) ORDER BY "Aco"."lft... ^
I think this error appears due to the fact that the component ACL is linked to a database which is the default.

Related

Delete on cascade in Model Laravel with eloquent

I want to delete data through the api but it is showing an error because it is necessary to delete records in the properties table.
SQLSTATE[23000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server] The DELETE statement conflicted with the REFERENCE constraint "FK_Interests_Properties_User". The conflict occurred in database "CADASTRO", table "dbo.Interests_Properties", column 'interests_user_id'. (SQL: delete from [Interests_User] where [user_id] = 1515626)
I created the model that performs actions on the Interests_Properts table, but when I try to delete the data that has the same interests_user_id, errors are occurring.
InterestsUser.php:
use App\Source\InterestsProperties;
class InterestsUser extends Model
{
protected $connection = 'sql_cadastro';
protected $table = 'Interests_User';
protected $primaryKey = 'id';
public $timestamps = false;
public function properties()
{
$this->belongsToMany(InterestsProperties::class, 'foreign_key');
}
public static function lgpdInterestsUser($id_user, $action)
{
if ($action == 'search') {
$data = InterestsUser::where('user_id', $id_user)->get();
if (count($data) > 0) {
return $data;
} else {
return false;
}
} elseif ($action == 'delete') {
$data = InterestsUser::with('properties')->where('user_id', $id_user)->get();
foreach ($data->properties as $p) $p->delete();
if ($data > 0) {
return 'Success Remove.';
} else {
return 'Not Found.';
}
} else {
return "Action Incorrect!";
}
}
}
InterestsProperties.php
class InterestsProperties extends Model
{
protected $table = 'Interests_Properties';
protected $primaryKey = 'id';
public $timestamps = false;
}
The error is occurring when trying to remove with cascade:
Call to undefined method Illuminate\Database\Eloquent\Builder::foreign()
Table Structure
Interests_User
id
interest_id
user_id
created_at
updated_at
Interests_Properties
id
interests_user_id
key
value
created_at
updated_at
At DB level, using onDelete: when migrating your InterestsProperties model you'll have a line like
$table->foreignId('foreign_key')
to that add ->onDelete('cascade')
after that update each time you delete a record from the main table it will do it in this one to.
At PHP level,
$data = InterestsUser::with('properties')->where('user_id', $id_user)->first();
foreach($data->properties as $p) $p->delete();
PD: Those will remove the property record too.

SQLSTATE[23502]: Not null violation: 7 ERROR - laravel

Below given is an API to upload files.
it shows error -
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column \"Userid\" of relation \"files\" violates not-null constraint\nDETAIL: Failing row contains (7, null, Distance Learning Promo.mp4, null, null, null, 2021-07-07 13:38:07, 2021-07-07 13:38:07). (SQL: insert into \"files\" (\"FileName\", \"updated_at\", \"created_at\") values (Distance Learning Promo.mp4, 2021-07-07 13:38:07, 2021-07-07 13:38:07) returning \"id\") .
And Postman shows the status 500 internal status error.
I don't think my Userid column here is null . Pls help me with some suggestions
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Uploads;
use Illuminate\Support\Facades\Auth;
class UploadController extends Controller
{
public function __construct()
{
$this->middleware('auth:api');
}
public function upload(Request $request)
{
$file=$request->file('file_name');
$fileName=$file->getClientOriginalName();
$folder = uniqid().'-'.now()->timestamp;
$file->storeAs('public/other-document/'.$folder, $fileName);
$filePath = $folder.'/'.$fileName;
$dataToInsert = array();
$dataToInsert['FileName'] = $fileName;
$dataToInsert['FilePath'] = $filePath;
if($request->has('uploadType'))
{
$dataToInsert['FileType'] = $request->uploadType;
}
$dataToInsert['uploadedBy'] = Auth::user()->id;
$dataToInsert['Userid'] = $request->bearerToken();
Uploads::create($dataToInsert);
}
}
Migration file
Schema::create('files', function (Blueprint $table) {
$table->id();
$table->string('Userid');
$table->string('FileName');
$table->string('FilePath');
$table->string('FileType');
$table->integer('uploadedBy');
$table->timestamps();
});
$dataToInsert['Userid'] = $request->bearerToken(); // error is here
if(!$dataToInsert['Userid']){
return "Null value in userID";
}
Check the $dataToInsert['Userid'] holds any value.
Also make Sure that Your are Passing bearerToken in header

SQLSTATE[23502]: Not null violation: 7 Laravel API error

Below is an API to upload files, and it displays the following error.
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "Userid" of relation "files" violates not-null constraint\nDETAIL: Failing row contains (7, null, Distance Learning Promo.mp4, null, null, null, 2021-07-07 13:38:07, 2021-07-07 13:38:07). (SQL: insert into "files" ("FileName", "updated_at", "created_at") values (Distance Learning Promo.mp4, 2021-07-07 13:38:07, 2021-07-07 13:38:07) returning "id")
Also, Postman shows the status 500 internal status error. I don't think my Userid column here is null. Even if Userid column is inserted a dummy value like this: $dataToInsert['Userid'] =1. Also, it shows the same error.
Controller
class UploadController extends Controller
{
public function __construct()
{
$this->middleware('auth:api');
}
public function upload(Request $request)
{
$file = $request->file('file_name');
$fileName = $file->getClientOriginalName();
$folder = uniqid() . '-' . now()->timestamp;
$file->storeAs('public/other-document/' . $folder, $fileName);
$filePath = $folder . '/' . $fileName;
$dataToInsert = array();
$dataToInsert['FileName'] = $fileName;
$dataToInsert['FilePath'] = $filePath;
if ($request->has('uploadType')) {
$dataToInsert['FileType'] = $request->uploadType;
}
$dataToInsert['uploadedBy'] = Auth::user()->id;
$dataToInsert['Userid'] = $request->bearerToken();
Uploads::create($dataToInsert);
}
}
Migration
Schema::create('files', function (Blueprint $table) {
$table->id();
$table->string('Userid');
$table->string('FileName');
$table->string('FilePath');
$table->string('FileType');
$table->integer('uploadedBy');
$table->timestamps();
});
I am so sorry. I can't write comments yet. But did you add fields to Model fillable array?
I had a similar problem. And that was because i didn't add that field to fillable array of Model.

Laravel PostgreSQL Issue on updateOrCreateGroup

when I use updateOrCreate method on MySQL it's working fine on both conditions create or update. but when I use in PostgreSQL it's update is fine but when creates, show this error:
"SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "group_id" violates not-null constraint DETAIL: Failing row contains (null, aaa, 2020-06-24 17:14:54, 2020-06-24 17:14:54). (SQL: insert into "groups" ("group_id", "title", "updated_at", "created_at") values (?, aaa, 2020-06-24 17:14:54, 2020-06-24 17:14:54) returning "group_id")"
my code:
protected $primaryKey = 'group_id';
protected $guarded = [''];
public $incrementing = true;
public function updateOrCreateGroup($data, $id)
{
return $this::updateOrCreate(
['group_id' => $id],
$data
);
}

Cakephp dropdown list (selectlist) + how to display a value from the model and a related model

I would like to display in a dropdownlist (selectlist) that concatenated the value of a field form the model and and a field from a related model. I have a table 'working_day' which is linked to a table 'user' and 'pause'. In the view 'Pause'(add and edit), I have a dropdownlist that displays the working_day_id but I wish to displays the fields 'date' of 'WorkingDay' and the fields 'username' of 'User'.
For example : 13/04/2016 (jerome S).
I already tried $virtualfield, it work when i use field from 'WorkingDay' but it does not work when i use the field from 'User'.
db schema
the $virtualfield that i tried :
public $virtualFields = array('workingday_display_field' => 'concat(WorkingDay.date_working_day, " (", User.username, ")")');
public $displayField = 'workingday_display_field';
I also tried the solution proposed below but it does not work, the same problem occurs :
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->virtualFields['workingday_display_field'] = sprintf('concat(%s.date_working_day, " (", %s.username, ")")', $this->alias, $this->User->alias);
$this->displayField = "workingday_display_field";
}
Does anyone know how to solve the problem?
Thanks in advance.
There are some issues with doing it this way when using a different Model alias, another recommended way is to handle these in the Models construct method:
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->virtualFields['name'] = sprintf('CONCAT(%s.first_name, " ",%s.last_name)', $this->alias, $this->alias);
$this->virtualFields['namewithemail'] = sprintf('CONCAT(%s.first_name, " ", %s.last_name, " (", %s.email, ")")', $this->alias, $this->alias, $this->alias);
$this->displayField = "namewithemail";
}
This is described in this section of the book: http://book.cakephp.org/2.0/en/models/virtual-fields.html#virtual-fields-and-model-aliases
I have a similar situation where I need to create a list that combines two fields from different tables. What I ended up doing was overriding find() to return the appropriate list.
public function find($type = 'first', $params = array()) {
$workingdays = array();
if ($type == 'list'){
$params = array_merge(
array('contain' => array('User')),
$params
);
$workingdaysUnformatted = parent::find('all', $params);
foreach($workingdaysUnformatted as $workingday){
$workingdays['WorkingDay']['workingday_display_field'] = $workingday['WorkingDay']['date'].' ('.$workingday['User']['username'].')'
}
}
else
$workingdays = parent::find($type, $params);
return $workingdays;
}
There may be a classier way to format the list that you want to return, but this illustrates the general idea.

Resources