Reputation: 57
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'
Upvotes: 4
Views: 8686
Reputation: 1031
If you want to use Eloquent then you should:
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 :)
Upvotes: 2
Reputation: 34914
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.
Upvotes: 3