查询构造器也可以使用 join 语法,看看下面的例子:
基本的 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();
你也可以指定更高级的 join 子句:
DB::table("users")
->join("contacts", function($join)
{
$join->on("users.id", "=", "contacts.user_id")->orOn(...);
})
->get();
如果你想在你的 join 中使用 where 型式的子句,你可以在 join 子句里使用 where 或 orWhere 方法。下面的方法将会比较 contacts 数据表中的 user_id 的数值,而不是比较两个字段。
DB::table("users")
->join("contacts", function($join)
{
$join->on("users.id", "=", "contacts.user_id")
->where("contacts.user_id", ">", 5);
})
->get();