代码之家  ›  专栏  ›  技术社区  ›  BalG Lal Shrestha

Laravel雄辩地实现了两个表的内部连接

  •  4
  • BalG Lal Shrestha  · 技术社区  · 8 年前

    我需要让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'
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   Niklesh Raut    8 年前

    你可以申请 inner join 就像拉雷维尔这样 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();
    

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

        2
  •  2
  •   Radu    8 年前

    如果你想使用雄辩,那么你应该:

    1. 创建与materials和materials_lists表关联的模型。
    2. 在两个模型之间建立如下关系:

    在“材质模型”类中,应具有一对多类型关系:

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

    在MaterialsLists模型类中,以相反的方式显示“belongsTo”类型的关系。

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

    3.然后您可以从Materials对象中引用MaterialsList对象属性,如下所示:

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

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

    如果Eloquent不是强制性的,那么您可以将查询生成器中的连接方法与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()
    

    希望有帮助:)