我使用两个表的内连接进行简单的选择查询。问题是,当我返回标题时,我才收到此错误:
尝试获取非对象的属性
但是当我返回所有的json时,它的效果非常好。我想用标题来查询。我该如何解决这个问题?
$products = DB::table('products');
$messages = $products
->join('bookings', 'products.id', '=', 'bookings.ProductID')
->where('EmailAddress', '=', ''. $userEmail . '')
->orderBy("bookings.DateCreated", "desc")
->get();
return $messages->Title;
答案 0 :(得分:0)
您的代码或查询返回多个Result,因此您需要循环或迭代它: -
$products = DB::table('products');
$messages = $products
->join('bookings', 'products.id', '=', 'bookings.ProductID')
->where('EmailAddress', '=', ''. $userEmail . '')
->orderBy("bookings.DateCreated", "desc")
->get();
return $messages->Title;
根据您的代码,您似乎只需要第一行结果,因此将代码更改为(replace - > get()with - > first()): -
$products = DB::table('products');
$messages = $products
->join('bookings', 'products.id', '=', 'bookings.ProductID')
->where('EmailAddress', '=', ''. $userEmail . '')
->orderBy("bookings.DateCreated", "desc")
->first();
return $messages->Title;
答案 1 :(得分:0)
为什么不能尝试使用Eloquent Eager Loading。所以你将获得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.
答案 2 :(得分:0)
感谢答案。但我找到了解决方案。我曾经在内部加入并添加别名。
$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);;