如何在Laravel中联接两个不同的表

时间:2018-08-14 15:58:33

标签: php database laravel join eloquent

  Connection.php第729行中的

QueryException:   SQLSTATE [42S22]:找不到列:1054中的未知列'site_name'   “ where子句”(SQL:从中选择email_dateurlrecipient   report_list,其中site_name = mywebsite)

$records = DB::table('report_list')
              ->select('email_date','url','recipient') 
              ->where('site_name',$site_name)
              ->get();
return records;

return view('monthlyReport')
           ->with('records',$records)
           ->with('site_name',$site_name);

我的site_name在不同的桌子上,我不知道是否需要为这两个放置Join或Make a model。

有人可以帮助我进行此查询吗?

3 个答案:

答案 0 :(得分:0)

如果显示表以查看列和表名,则可以更好地帮助您,以下是一些示例:

//Option 1            
$results = DB::table('users')
->join('business', 'users.id', '=', 'business.user_id')
->select('users.*', 'business.name', 'business.telephone', 'business.address')
->get();

//Option 2
$results = User::join("business as b","users.id","=","business.user_id")
->select(DB::raw("users.*"), "b.name as business_name", "b.telephone as business_telephone", "b.address as business_address")                        
->get();

laravel文档:https://laravel.com/docs/5.6/queries#joins

答案 1 :(得分:0)

您应该为其他表创建一个模型,假设它是Site,然后在report_list模型中创建一个类似以下的关系方法:

public function sites(){
   return $this->hasOne(Site::class);
}

或:

public function sites(){
   return $this->hasOne('App\Models\Site);
}

之后,在雄辩的查询中使用以下命令:

$records = DB::table('report_list')
              ->select('email_date','url','recipient') 
              ->whereHas('sites', function($query){
                        $query->where('site_name',$site_name);
               })
              ->with('sites')
              ->get();

答案 2 :(得分:0)

  1. 首先,您需要在数据库的“ report_list”表中添加名为“ site_name”的列。
  2. 此查询供您连接2个表(此处我以示例“ users”表作为第二个表,如果第二个表不同,请使用您的表)->

    $records = DB::table('report_list')
                        ->join('users', 'report_list.user_id', '=', 'users.id')
                        ->where('report_list.site_name', '=', $site_name);
                        ->select('users.*', 'report_list.email_date','report_list.url','report_list.recipient')
                        ->get();
        return view('monthlyReport')
               ->with(['records' => $records , 'site_name' => $site_name ]);