简体   繁体   中英

Many to many relationship retrieve a column connected to pivot table in Laravel

I have a many to many relationships (pivot). There are 3 tables, namely banks, principles, and bank_principles. Under Principles, I want to get the principle column to show under the Banks table. The bank_principle table consists of bank_id and principle_id. I want to retrieve principle column under the Principle table and have it shown under the Banks data when I run it in the console. How can it be done?

My controller:

$bankTransfer = Banks::with('principles')->get();

My pivot relationship under banks:

return $this->belongsToMany('App\Models\Principle', 'bank_principle', 'bank_id', 'principle_id')->using('App\Models\BankPrinciple');

My pivot relationship under principle:

return $this->belongsToMany('App\Models\Banks', 'bank_principle');

Loop through $bankTransfer to access individual $bankTransfer object and then loop through $bankTransfer->priciples to access individual principle .

foreach($bankTransfer as $bankTransferEach){
    //here you can access bank transfer data like $bankTransferEach->account_number
      foreach($bankTransferEach->principles as $principle){
          //here you can access principle table data like $principle->column_name
      }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM