【问题标题】:Sort the parent model based on the child model / relationship根据子模型/关系对父模型进行排序
【发布时间】:2019-02-23 11:13:37
【问题描述】:

我有一个名为appointments 的模型,每个约会都有一个option_id,通过一对一的关系链接,option_id 也可以是null。选项模型具有属性datetime_start。我想根据option.datetime_start 对约会进行排序。

这是我的代码:

$appointments = $user->appointments()
->with(['option'
])
->get();

编辑:

约会模式:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Appointment extends Model
{
   /**
         * @return \Illuminate\Database\Eloquent\Relations\HasOne
   */
   public function option()
   {
     return $this->hasOne(Option::class, 'id', 'option_id');
   }
}

选项型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Option extends Model
{
    protected     $fillable = ["appointment_id",
                               "datetime_start"
    ];

    public function appointment()
    {
        return $this->belongsTo(Appointment::class, 'id','appointment_id');
    }
}

任何帮助将不胜感激。

【问题讨论】:

  • 能否添加AppointmentOption 型号的代码?它使您更容易解决问题。

标签: mysql laravel orm model eloquent


【解决方案1】:

为了通过相关 Option 模型中的列对 Appointment 模型进行排序,您需要在查询中添加 JOIN 以便您可以按相关字段排序:

$appointments = $user->appointments()
  ->leftJoin('options', 'options.appointment_id', '=', 'appointments.id')
  ->orderBy('options.datetime_start', 'ASC')
  ->with(['option'])
  ->get();

这将为您提供所有约会,包括那些没有 Option 的约会 - 那些没有 Option 并且因此没有 datetime_start 的约会将是all 在结果列表的开头或结尾返回,您需要检查一下。如果您只想使用 Option 进行约会,请将 leftJoin() 替换为 join()

【讨论】:

    【解决方案2】:

    $appointments = Appointment::with(['option' =&gt; function ($query){ $query-&gt;orderBy('datetime_start', 'desc'); } ])-&gt;get();

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    猜你喜欢
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 2017-08-21
    • 2012-01-29
    • 2016-12-31
    • 1970-01-01
    • 2013-04-17
    • 2013-08-11
    相关资源
    最近更新 更多