简体   繁体   中英

Get all data of foreign key in laravel

Currently i am doing this to get branch table data:

$smlist = SM::where('branch_id','=',$branchid)->select('id','name','branch_id')->get();
    foreach ($smlist as $sm) {
      $sm->b = SM::find($sm->id)->branch;
    }

Where branch_id is foreign key, also I set belongsTo in SM table.
This is working fine for me but I am finding way to use it with in single query. How can i get this data using single query?

You can eager load your relationship using with() :

$smlist = SM::with('branch')
            ->where('branch_id','=',$branchid)
            ->select('id','name','branch_id')
            ->get();

You have to use a join, here you can find the documentation http://laravel.com/docs/4.2/queries#joins

I think you can use something like this:

SM::->join('branch', 'branch.id', '=', 'sm.branch_id')
.where('sm.branch_id','=',$branchid)
->select('sm.id','sm.name','sm.branch_id','branch.name')
->get();

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