简体   繁体   中英

Laravel eloquent to implement inner join for two tables

I need to get Laravel eloquent to implement inner join for two tables

select materials.id, 
        material_lists.name, material_lists.cost, 
        colors.code, colors.hex, colors.name,
        materials.color_cost, materials.estimation, materials.remarks
    from materials 
    inner join  
    material_lists on materials.material_id = material_lists.id 
    inner join
    colors on colors.id = materials.color_id 
    where carpet_id = '2'

You can apply inner join like this with laravel query builder DB

$result = DB::table("materials as m")
->join("material_lists as ml","ml.id","=","m.material_id")
->join("colors as c","c.id","=","m.color_id")
->where('m.carpet_id',2)
->select("m.id", 
        "ml.name", "ml.cost", 
        "c.code", "c.hex", "c.name",
        "m.color_cost", "m.estimation", "m.remarks")
->get();

Share your model and relation if you made.

If you want to use Eloquent then you should:

  1. Create models associated to materials and materials_lists table.
  2. Establish relationships between the two models something like this:

In the material model class you should have a one to many type relationship:

 public function MaterialsList {
    return $this->haveMany ('MatrialLists_ModelName')
 }  

and a 'belongsTo' type relationship in the opposite way in the MaterialsLists model class.

 public function Materials {
    return $this->belongsTo ('Materials_ModelName')
 }  

3. Than you can reference MaterialsList object properties from Materials object like that:

 $materialsListCollection = $materials ->MaterialsLists->all(); 

where $materials is a instantion of Materials Model.

If Eloquent is not mandatory, than you can use join method from Query Builder with DB facade something like that:

$collection = DB::table('materials')
 join('material_lists' , 'materials.id' , '=','material_lists,id') -> 
 join('colors' , 'colors.id' , '=','materials.colors,id') -> 
 select ('materials.id', 'material_lists.name', 'material_lists.cost', 
    'colors.code', 'colors.hex', 'colors.name' 'materials.color_cost', 
     'materials.estimation', 'materials.remarks') 
      ->where('carpet_id' , '2')->get()

Hope it helps :)

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