Laravel内部连接仅返回特定结果


Laravel inner join to return specific result only

>我有一个简单的选择查询,使用两个表的内部连接。问题是当我只返回标题时,我收到此错误:

尝试获取非对象的属性

但是当我返回所有 json 时,它运行良好。我想使用标题进行查询。如何解决此问题?

    $products = DB::table('products');
    $messages = $products
        ->join('bookings', 'products.id', '=', 'bookings.ProductID')
        ->where('EmailAddress', '=', ''. $userEmail . '')
        ->orderBy("bookings.DateCreated", "desc")
        ->get();
    return $messages->Title;

您的代码或查询返回多个结果,因此您需要循环或迭代它:-

$products = DB::table('products');
$messages = $products
    ->join('bookings', 'products.id', '=', 'bookings.ProductID')
    ->where('EmailAddress', '=', ''. $userEmail . '')
    ->orderBy("bookings.DateCreated", "desc")
    ->get();
return $messages->Title;

根据您的代码,您似乎只需要第一行结果,因此请将代码更改为(将 ->get() 替换为 ->first()) :-

$products = DB::table('products');
$messages = $products
    ->join('bookings', 'products.id', '=', 'bookings.ProductID')
    ->where('EmailAddress', '=', ''. $userEmail . '')
    ->orderBy("bookings.DateCreated", "desc")
    ->first();
return $messages->Title;

为什么你不能尝试使用雄辩的渴望加载。因此,您将获得对象返回。

$messages = Products::with(['bookings' => function ($query) use ($userEmail) {
    $query->where('EmailAddress', '=', ''. $userEmail . '');
    $query->orderBy("bookings.DateCreated", "desc");
}])->get();
Try similar like this. Hope you will get the collection.

感谢答案。但我找到了我的解决方案。我曾经内部连接并放置别名。

    $products = DB::table('products');
    $messages = $products
        ->join('bookings AS b1', 'products.id', '=', 'b1.ProductID')
        ->join('booking_notifications as b2', 'b1.Code', '=', 'b2.Code')
        ->where('Products.EmailAddress', '=', ''. $userEmail . '')
        ->orderBy("b1.DateCreated", "desc")       
        ->get(); 
    return view('messages.index')->with('messages', $messages);;