總結一下 復雜查詢的方法:
普通的join查詢
DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.id', 'contacts.phone', 'orders.price')
->get();
Left Join 聲明語句
DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
//select * from users where name = 'John' or (votes > 100 and title <> 'Admin')
//這里注意一下 想要對where條件里面的東西繼續劃分,可以利用$query 執行查詢器
DB::table('users')
->where('name', '=', 'John')
->orWhere(function($query)
{
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get();
問題一,如果想要對join里查出的東西 再進行條件劃分,怎么做呢。看個例子
主要是 $join->on('這里放置聯合查詢條件')->where(操作的條件)
DB::table('goods')
->select('goods.*')
->distinct('goods.id')
->join('goods_auction',function ($join) use (&$user){
$join->on('goods.id','=','goods_auction.goods_id')
->where('goods_auction.buyer_id','=',$user['id']);
});
這里&$user 是上文傳過來的數據,可以進行操作