在多对多关系中按字段排序(Laravel)

时间:2019-11-05 18:54:27

标签: php laravel

我有一个模型School,其中有一个EmiratesToMany关系:

create table temp_ns as 
    select nearbystopname, latitude, longitude, mainaddress, 
           row_number() over (partition by nearbystopname, mainaddress) as seqnum
    from DUSAgeocodeDB.nearbystops ns;

truncate table DUSAgeocodeDB.nearbystops ns;  -- SAVE first!!!

insert into DUSAgeocodeDB.nearbystops (nearbystopname, latitude, longitude, mainaddress)
    select nearbystopname, latitude, longitude, mainaddress
    from temp_ns
    where seqnum = 1;

如何通过活动start_at字段订购学校?例如,我可以这样吗?

class School extends Model
{
    protected $fillable = [
        "url",
        "title",
        "is_own",
    ];

    public function events()
    {
        return $this->belongsToMany(Event::class, "event_school");
    }
}

可以吗?请告诉我如何实施。谢谢。

UPD: 我尝试使用join,是的,但是不能正常工作:

School::whereHas("events")
    ->with([
        "events" => function ($query) {
            $query->latest("start_at")->limit(4);
        },
        "events.address"
    ])->orderBy("events.start_at")->paginate(4);

我会得到所有事件。 Schools::whereHas("events") ->select("schools.*") ->join("event_school", "schools.id", "=", "event_school.school_id") ->join("events", function ($join) { $join->on("events.id", "=", "event_school.event_id") ->whereDate("events.start_at", ">=", Carbon::now()->format("Y-m-d")) ->limit(4); }) ->join("addresses", "events.address_id", "=", "addresses.id") ->groupBy("schools.id") ->orderBy("events.start_at") 无法正常工作,也无法加载地址

1 个答案:

答案 0 :(得分:1)

解决方案:

    School::whereHas("events")
        ->select("schools.*")
        ->join("event_school", "schools.id", "=", "event_school.school_id")
        ->join("events", function ($join) {
            $join->on("events.id", "=", "event_school.event_id");
        })
        ->with([
            "events" => function ($query) {
                $query->whereDate("start_at", ">=", Carbon::now()->format("Y-m-d"))
                    ->orderBy("start_at", "asc")
                    ->limit(4);
            },
            "events.address"
        ])
        ->groupBy("schools.id")
        ->orderBy("events.start_at");