【问题标题】:Show user only those products which he hasn't buyed using laravel eloquent使用 laravel eloquent 仅向用户显示他没有购买的产品
【发布时间】:2020-10-26 12:20:36
【问题描述】:

是否有任何直接查询,我们可以使用 laravel eloquent 功能仅向用户显示登录用户尚未购买的产品

我是 laravel 关系和雄辩查询的新手

直到现在我已经尝试使用类似的查询

DB::raw('Select * from products 
where products.id not in ( "Select product_id from order_product
left join orders on orders.id = order_product.order_id 
left join users on users.id = orders.user_id 
where users.id='.$user_id.'")');

【问题讨论】:

  • 欢迎来到SO ...到目前为止您尝试了什么?你猜你会怎么做?
  • 伪代码:Product::whereDoesntHave('user', function($query) { $query->where("id", Auth::id()); });
  • 我是 laravel eloquent 的新手,我被这个查询卡住了,但找不到我通常用原始查询尝试的简单答案,有没有更好的解决方案。
  • 对某事有新意是可以的 :) ...您将如何使用原始查询来做到这一点?你对这些表的模型有任何关系设置吗?
  • 是的,我在模型中设置了关系,我有一个产品和用户模型,但正在寻找最佳解决方案。

标签: php mysql laravel eloquent


【解决方案1】:

你可以试试这样的,它会解决你的问题

$user_id = auth()->user()->id;

Product::where('status', 'active')

  ->whereNotIn('id', function($query) use ($user_id) {

    $query->select('product_id')->from((new OrderProduct)->getTable())

      ->where('user_id', $user_id)->where('status', 'delivered')

        ->pluck('product_id')->toArray();

  });

【讨论】:

  • 当您可以创建一个关系并使用诸如whereHas()whereDoesntHave() 之类的关系查询时,为什么要让它如此复杂?
  • 好的,谢谢你的建议,我一定会在这部分工作,以解决更多 laravel 雄辩的问题 :)
猜你喜欢
  • 1970-01-01
  • 2016-10-01
  • 1970-01-01
  • 2015-07-30
  • 2016-09-21
  • 1970-01-01
  • 2021-03-17
  • 2013-12-05
  • 1970-01-01
相关资源
最近更新 更多