Home > Software engineering >  Laravel get column name using child table with eager loading
Laravel get column name using child table with eager loading

Time:10-04

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();

CodePudding user response:

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