【问题标题】:Laravel inner join to return specific result onlyLaravel 内连接仅返回特定结果
【发布时间】:2016-07-14 02:26:51
【问题描述】:

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

试图获取非对象的属性

但是当我返回所有 json 时,它工作得很好。我想用标题来查询。我该如何解决这个问题?

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

【问题讨论】:

  • $messages 是一个数组,而不是一个对象。遍历数组。
  • 好的,谢谢。我会试试的。但是我想用标题来查询?

标签: php sql laravel model-view-controller


【解决方案1】:

您的代码或查询返回多个 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;

【讨论】:

    【解决方案2】:

    您为什么不能尝试使用 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.
    

    【讨论】:

      【解决方案3】:

      感谢答案。但我找到了我的解决方案。我以前是内连接并放别名的。

          $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);;
      

      【讨论】:

      • 这不应该工作,应该抛出同样的错误。
      猜你喜欢
      • 2013-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      相关资源
      最近更新 更多