加入Laravel的3张桌子

时间:2016-09-10 02:49:31

标签: php laravel

我想加入这3张桌子。

代表团

  • delegation_id
  • 代表团

代表

  • delegates_id
  • delegatesname
  • delegations_id

  • delegates_id
$meals = Meal::join('delegates', 'delegates.delegates_id', '=', 'meals.delegates_id')
    ->join('delegates', 'delegates.delegations_id', '=', 'delegates.delegations_id')
    ->get();

3 个答案:

答案 0 :(得分:0)

在控制器中编写以下代码

use DB;

在控制器函数

中编写以下查询
  $meals=DB::select("SELECT delegations .*, delegates .*,  meals.*
    FROM delegations 
        JOIN delegates
            ON delegates.delegations_id = delegations.delegations_id
        JOIN meals
            ON meals.delegates_id = delegates.delegates_id");

答案 1 :(得分:0)

你为什么要这样做"手动"如果你使用laravel?查看此参考eloquent-relationship

在这种情况下只需在模型中定义(这些是概念示例,我无法确定您的项目结构):

膳食

function delegate(){
  $this->belongsTo(Delegate::class);
}

代表

function delegation(){
  $this->belongsTo(Delegate::class);
}


function meal(){
  $this->hasOne(Meal::class);
}

 function delegates(){
      $this->hasMany(Delegate::class);
    }

然后你可以这样做:

$meals = Meal::all();  
foreach ($meals as $meal){
    $delegates = $meal->delegate;
    $delegation = $mealt->delegate->delegation;
}

您可以在刀片上的控制器上使用它,然后您将获得所需的所有信息,例如$ delegate-> name,$ delegation-> id an so on

答案 2 :(得分:-1)

您可以通过两种方式实现:

1.-原始查询

use DB;
public static function getRaw_data(){
  return DB::select("SELECT d1.*, d2.*, m.* 
                     FROM delegations d1, delegates d2, meals m 
                     WHERE d1.delegations_id = d2.delegations_id AND d2.delegates_id = m.delegates_id );        

}

2 .-

    use DB;
    public static function getRaw_data(){
            return DB::table('delegations')
                  ->join('delegates','delegations.delegations_id','=','delegates.delegations_id')
                  ->join('meals','delegates.delegates_id','=','meals.delegates_id')
                  ->select('delegations.*','delegates.*','meals.*')
                  ->get();
        }