Laravel eloquent实现两张表的内连接

Laravel eloquent to implement inner join for two tables

我需要获取 Laravel eloquent 来实现两个表的内部连接

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'

可以申请inner join like this with laravel query builderDB

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

如果你做了,请分享你的模型和关系。

如果你想使用 Eloquent 那么你应该:

  1. 创建与 material 和 materials_lists table 关联的模型。
  2. 像这样在两个模型之间建立关系:

在 material 模型中 class 你应该有一个一对多类型的关系:

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

和 MaterialsLists 模型中的 'belongsTo' 类型关系 class。

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

3。你可以像这样从 Materials 对象引用 MaterialsList 对象属性:

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

其中 $materials 是材料模型的实例。

如果 Eloquent 不是强制性的,那么您可以使用 Query Builder 中的连接方法和 DB facade 之类的东西:

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

希望对您有所帮助:)