Laravel get column name using child table with eager loading - laravel

I want to fetch the data from profile table using a child table of other parent table.
Here is the tables
Profile table
id
profile_name
Transaction table
id
transaction_name
Sub transaction table
id
transaction_id
profile_id
Now i want to get the profile name from transaction model using eager loading . i tried has one Though relationship in transaction model but returning null
Here is my relationship in Transaction model
public function profileName()
{
return $this->hasOneThrough(
Profiler::class,
SubTransaction::class,
'profile_id',
'id',
'id',
'transaction_id',
);
}
Here is where i am trying to fetch from transaction controller
$options = Transaction::with([
'profileName:id,profile_name as profileName',
])
->get();

It returns null because I think you have a little problem about matching between foreign keys and local keys. You could try the following code:
return $this->hasOneThrough(
Profiler::class, //Final model we wish to access
SubTransaction::class, //The name of the intermediate model
'transaction_id', //Foreign key on sub_transaction table
'id', //Foreign key on profile table
'id', //Local key on transaction table
'profile_id', //Local key on sub_transaction table
);
If you have any problem, tell me.

Related

How to delete record with composite primary keys using Eloquent?

I'm trying to delete a record with two primary keys, using Eloquent - Laravel.
This is my model
class Like extends Model
{
//protected $primaryKey = ['crdid', 'usrid'];
public $timestamps = false;
use HasFactory;
}
Controller
try{
$dellike = Like::where('crdid', '=', $like->crdid, 'and')
->where('usrid', '=', $like->usrid)->first();
$dellike->delete();
}
catch(Exception $e){
return $e->getMessage();
}
Table definition
Schema::create('likes', function (Blueprint $table) {
$table->biginteger('crdid');
$table->biginteger('usrid');
$keys = array('crdid', 'usrid');
$table->primary($keys);
});
However, it gives me the below error;
Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: delete from `likes` where `id` is null)
I believe the 'id' is the default primary key used by Eloquent, but I'm not using it.
How should I define that, I'm not using the default primary key? or what is the correct way to delete the record with composite primary keys? Any help would be highly appreciated.
As Laravel Eloquent Docs says:
Eloquent requires each model to have at least one uniquely identifying "ID" that can serve as its primary key. "Composite" primary keys are not supported by Eloquent models. However, you are free to add additional multi-column, unique indexes to your database tables in addition to the table's uniquely identifying primary key.
So you can't use some methods of eloquent.
But seeing your code, looks like you are trying to create a model for a relationship pivot table (many to many between user and crd (what is crd?! no reason to abreviatte here.)
Try defining a many to many relationship on your user and crd model.
Also laravel naming convention for key columns is: model_name_id for a model named ModelName
But, just to delete, you can skip the first in your query:
Like::where('crdid', '=', $like->crdid, 'and')
->where('usrid', '=', $like->usrid)->delete();
This happens because when you delete a model (your attempt) laravel uses the primary key field (defaults to id) as where condition. But manually querying, you are defining the where clauses of the delete.
Just create additionnal column named id in the table as unique with auto-increment option. Eloquent will use it to delete each row with delete function.
Example with Laravel 5.5 :
$logement = Logement::findOrFail($id);
$commodites = Commodites_logement::all()->where('logement_id','=',$logement->id);
foreach ($commodites as $commodite) {
$commodite->delete();
}

Laravel hasManyThrough returning empty array

I need some help regarding hasManyThrough()
user_duty
id
user_id
date
duty_hours
sales_duty
id
user_id
date
total_sales
total_orders
income_table
id
sales_id (this is same as 'id' of sales_duty)
date (same as 'date' of sales_duty)
total_income
total_collection
I can relate sales_duty with income_table using (sales_id,date) these two keys.
I can also connect to sales_duty from user_duty based on (user_id,date)
Now I want to connect to user_duty to income_table
public function user_income()
{
return $this->hasManyThrough('App\IncomeTable','App\SalesTable','id','sales_id','id','id');
}
But its returning empty
According to the details you have provided it should be like this.
public function user_income()
{
return $this->hasManyThrough(
'App\IncomeTable',
'App\SalesTable',
'user_id', // Foreign key on sales_duty table...
'sales_id', // Foreign key on income_table...
'id', // Local key on user_duty table...
'id' // Local key on sales_duty table...
);
}

Laravel using pivot table to generate a raply from database in one request

I am using datatables so I need to make a request to my database and get a return in one json.
I have a table of users and a table that is linking the users to them to specify if they have a manager. I m doing this through a pivot table.
#User#
id
name
#User_user#
user_id
manager_id
I have the following model for the User.php:
public function managers()
{
return $this->belongsToMany('App\User', 'users_users' , 'user_id', 'manager_id')->withPivot('manager_type')->withTimestamps();
}
public function employees()
{
return $this->belongsToMany('App\User', 'users_users' , 'manager_id', 'user_id')->withPivot('manager_type')->withTimestamps();
}
In order to generate my data for Datatables, I am using:
$userList = $this->user->select('id', 'name','email','is_manager', 'region', 'country', 'domain', 'management_code', 'job_role', 'employee_type');
$data = Datatables::of($userList)->make(true);
This gives me the info I need except, I would like to add the manager so that I can use it in datatables. I don't understand how I can configure this in order to get this in 1 reply of the DB using Eloquent.

cakePHP 3 save data in Many to Many relationship

I have Employees and Complexes in a Many to many relationship.I have used the
bake console to generate models, controllers... for Employees and Complexes tables.
My questions is :
-Since I have in my BD The table "complexes_employees", do I have to bake also Model
and controller for this Table too or cakePHP is able to know that it contains the
two foreign keys of Employees and Complexes.
Second question :
-How can I save my data in this Three tables. for my app I have to save employees
per Complex .
// Employees Controller
public function addEmpPerComplex($id_complex){
$emp = $this->Employees->newEntity();
if ($this->request->is('post')) {
$employee = $this->Employees->patchEntity($employee, $this->request->data, ['associated'=>['Complexes._joinData']] );
//here I need to insert the record that contains the employee data in Employees Table
// then I need to insert in "complexes_employees" the ID of Complex sended in parametre of this function and the ID of the new Employee
Thanks for helping me
Do I have to bake also Model and controller for this Table?
No, CakePHP will use the abstract Table class. However, if you need extra information for this relationship, then you will need to create a join model. Check http://book.cakephp.org/3.0/en/orm/associations.html#using-the-through-option
How can I save my data in this Three tables?
As long as your data has the id of a related entity, it will automatically be saved both entity and relation:
$data = [
//employee data,
'complexes' => [
['id' => $id_complex]
]
]
$this->Employees->patchEntity($employee, $data, [
'associated' => ['Complexes']
]);
/*
Saves both the new Employee and the relation
(employeed id and complex id in complexes_employees)
*/
$this->Employees->save($employee);
For more information: http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-belongstomany-associations

Laravel - Many to Many Polymorphic Relation with Extra Fields

How can I define a many to many polymorphic relation with extra fields?
I have three (or more, as it is a polymorphic relation) tables.
tags table: id, name
tagged table: id, tag_id, taggable_id, taggable_type, user_id
posts table: id, record, timestamps
users table: id, name, email
The user_id on the tagged table referes to the users table on column id.
In my Post model I have:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable','tagged');
}
and in my Tag model I have:
public function posts()
{
return $this->morphedByMany('App\Post', 'taggable','tagged');
}
Then when I am try this in my controller:
$tag = new \App\Tag(
array(
'tag'=>"someTag"
));
$tag->save()
$post = \App\Post::find($id);
$post->tags()->save($tag);
I get Integrity Constraint Violation for not having a user_id:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (hb.tagged, CONSTRAINT tagged_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id)) (SQL: insert into tagged (tag_id, taggable_id, taggable_type) values (26, 2, App\Resource)).
Which is somewhat expected, as I have never had the chance to define or declare the user_id field.
Also, I have tried withPivot() on tags relation as follows, to no avail:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable','tagged')->withPivot('user_id');
}
Like in the comment: withPivot has nothing to do with saving/creating. If you want to pass additional pivot data when saving, do this:
$post->tags()->save($tag, ['user_id' => $userId]);

Resources