【问题标题】:Translating a MySQL query into Laravel Eloquent将 MySQL 查询翻译成 Laravel Eloquent
【发布时间】:2019-07-22 12:39:06
【问题描述】:

我想把下面的查询变成 Laravel Eloquent。

select * from tool where id not in (select tool_id from product_tool where product_id = 1) 

到目前为止,我已经尝试了以下方法。

$cari = Product::where('slug', $slug)->first();
if (empty($cari)) {
    abort(404);
}

$productTool = ProductTool::where('product_id', $cari->id)->get();
foreach ($productTool as $data) {
    $tools = Tool::whereNotIn('id', [$data->tool_id])->get();
}

问题是当我 dd() $tools 时,它只返回一个数组。它需要返回两个数组,因为在 product_tool 表中(与 products 和 tools 表是多对多的)product_id 1 有 tool_id 的 id [1,2]。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    你好,请试试这个是纯laravel eloquent。

    $cari = Product::where('slug', $slug)->first();
    
    if (empty($cari)) {
        abort(404);
    }
    
    $tools = Tool::whereNotIn('id', ProductTool::where('product_id', $cari->id)
    ->pluck('tool_id')->toArray())->get();
    

    【讨论】:

      【解决方案2】:
          $cari = Product::where('slug', $slug)->first();
      
          use get() instead of first()
      
       $cari = Product::where('slug', $slug)->get();
      
          when you use first() function it will return only one array.
          use get()
      

      【讨论】:

      • 我使用 first() 是因为,我不知道要告诉你,但是当我想展示一些东西时,它就像 findOrFail()。所以它就像找到一个 id 但我使用 slug。很抱歉,如果您感到困惑:'
      【解决方案3】:

      您的代码缺少 $tools[] ,通过将 [] 放在变量前面,它不会覆盖第一个键

       $tools = [];
       $cari = Product::where('slug', $slug)->first();
       if (empty($cari)) {
          abort(404);
      }
      $productTool = ProductTool::where('product_id', $cari->id)->get();        
      foreach ($productTool as $data) {
          $tools[] = Tool::whereNotIn('id', [$data->tool_id])->get();
      }
      

      因此 $tools 现在返回 2 个数组

      【讨论】:

      • $tools 现在返回 2 个数组。但是现在问题已经出现了,我试图 foreach $tools.但它给了我错误“此集合实例上不存在属性 [tool_name]。”tool_name 是表工具上的字段。
      猜你喜欢
      • 2015-11-07
      • 2013-09-13
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      • 2020-06-03
      • 1970-01-01
      • 2016-09-30
      相关资源
      最近更新 更多