简体   繁体   English

Laravel雄辩地为两个表实现内部联接

[英]Laravel eloquent to implement inner join for two tables

I need to get Laravel eloquent to implement inner join for two tables 我需要雄辩的Laravel来实现两个表的内部联接

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 您可以使用laravel 查询构建器 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: 如果您想使用Eloquent,则应该:

  1. Create models associated to materials and materials_lists table. 创建与materials和materials_lists表关联的模型。
  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. 在MaterialsLists模型类中以相反的方式创建“ belongsTo”类型关系。

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

3. Than you can reference MaterialsList object properties from Materials object like that: 3.比您可以像这样从Materials对象引用MaterialsList对象属性:

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

where $materials is a instantion of Materials Model. 其中$ materials是Material Model的实例。

If Eloquent is not mandatory, than you can use join method from Query Builder with DB facade something like that: 如果Eloquent不是必需的,则可以将查询生成器中的join方法与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()

Hope it helps :) 希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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