[英]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;
您的代碼或查詢返回多個Result,因此您需要循環或迭代它:-
$products = DB::table('products');
$messages = $products
->join('bookings', 'products.id', '=', 'bookings.ProductID')
->where('EmailAddress', '=', ''. $userEmail . '')
->orderBy("bookings.DateCreated", "desc")
->get();
return $messages->Title;
根據您的代碼,似乎只需要結果的第一行,因此將代碼更改為(-> first()替換-> get()):-
$products = DB::table('products');
$messages = $products
->join('bookings', 'products.id', '=', 'bookings.ProductID')
->where('EmailAddress', '=', ''. $userEmail . '')
->orderBy("bookings.DateCreated", "desc")
->first();
return $messages->Title;
為什么您不能嘗試雄辯的渴望加載。 這樣您將獲得Object返回。
$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);;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.