【问题标题】:Laravel sort order for both relationship and current table关系和当前表的 Laravel 排序顺序
【发布时间】:2020-07-10 11:23:04
【问题描述】:

我有一个评论表和 review_photos。我想通过其 updated_at 列从特定产品订单中获取所有评论,并优先考虑带有照片的评论,以便在特定日期内首先显示。下面的解决方案只会返回只有照片的评论,没有照片的评论不会显示。

审查模型

public function photos()
{
    return $this->hasMany('App\Models\Booking\ReviewPhoto');
}

查看照片模型

public function review()
{
    return $this->belongsTo('App\Models\Booking\Review');
}

评论库

public function getProductReviews($product_id, $paginate = false)
{
    $query = $this->review->where('product_id', $product_id)->whereHas('photos')->orderByDesc('updated_at');

    if ($paginate !== false) {
        return $query->paginate($paginate);
    }

    return $query->get();
}

【问题讨论】:

  • 你可以使用这样的东西。 $query = $this->review->where('product_id', $product_id)->orderByDesc('updated_at')->orderBy('photo_id'); 这将首先根据 updated_at 然后 photo_id 做短表,或者您可以将其更改为反之亦然。

标签: php laravel eloquent


【解决方案1】:

要获得无条件连接,可以使用with

$query = $this->review->where('product_id', $product_id)->with('photos')->orderByDesc('updated_at');

【讨论】:

    猜你喜欢
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2014-06-25
    • 2019-05-14
    • 2019-11-09
    • 2017-02-21
    • 1970-01-01
    相关资源
    最近更新 更多