【问题标题】:Laravel eloquent: Only retrieve entries where relationship has entries (join)Laravel 雄辩:只检索关系有条目的条目(加入)
【发布时间】:2021-02-22 04:15:56
【问题描述】:

我有一个products 和一个products_marks 表。 products_marks 表包含一个user_id 和一个product_id,代表用户标记/保存的所有产品。所以,这或多或少有点像观察名单。

我现在的目标是执行一个雄辩的查询,它只返回我也存在于product_marks 表中的某个user_id 的产品。对于这个例子,让我们选择user_id 2。

这是我的products.php 模型:

public function marks()
    {
        return $this->belongsToMany('App\Models\User', 'products_marks', 'product_id', 'user_id')->withTimestamps();
    }

这就是我目前想要实现的目标。

我使用join 执行了一个雄辩的查询。但是我怎样才能在一段关系中做到这一点呢?

$products = Product::join('products_marks', 'products_marks.product_id', '=', 'products.id')
            ->where('products_marks.user_id', 2)
            ->orderBy('created_at', 'desc')
            ->paginate(10);

诚挚的问候,谢谢!

【问题讨论】:

  • 有一个 has 方法和一个 whereHas 方法来满足您的需求
  • 我这里没有删除这个帖子?
  • 我说的是stackoverflow.com/questions/64768283,它是关于$product->end_date的日期格式
  • 反正你可以做一个map操作来获取你想要的dateTime$product = Product::where('id', '1')->get(); $modified = $product->map(function($item, $key) { return [ 'id' => $product->id, 'name' => $product->name, 'end_date' => $product->end_date->format('Y-m-d H:i:s') ]; }); dd($modified['end_date']); // 2020-12-09 21:59:59
  • 我很抱歉...我删除了它,因为这个问题是同一时间的,所以没有必要......

标签: php mysql laravel join eloquent


【解决方案1】:

使用has 方法:

$products = Product::has('marks')->where('products_marks.user_id', 2)
                ->orderByDesc('created_at')
                ->paginate(10);

检查文档 https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 2015-03-14
    • 2018-11-28
    相关资源
    最近更新 更多