Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 多对多关系中按字段排序(Laravel)_Php_Laravel - Fatal编程技术网

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

Php 多对多关系中按字段排序(Laravel),php,laravel,Php,Laravel,我有一所模范学校,它有自己的亲戚关系: class School extends Model { protected $fillable = [ "url", "title", "is_own", ]; public function events() { return $this->belongsToMany(Event::class, "event_school"); } } 我

我有一所模范学校,它有自己的亲戚关系:

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

    public function events()
    {
        return $this->belongsToMany(Event::class, "event_school");
    }
}
我如何通过现场活动开始订购学校?例如,我可以这样做吗

School::whereHas("events")
    ->with([
        "events" => function ($query) {
            $query->latest("start_at")->limit(4);
        },
        "events.address"
    ])->orderBy("events.start_at")->paginate(4);
可能吗?请告诉我如何实现这一点。谢谢

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

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")

我要参加所有的活动<代码>->whereDate(“事件.开始时间“,”>=”,Carbon::now()->格式(“Y-m-d”)不工作,不加载地址解决方案:

    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");

更新后,您仍然可以(也应该)在此连接旁边使用带()的
->
。如果您不这样做,并尝试访问
$school->events
(这是Laravel关系),您将获得所有相关事件,而不是最新的4个。@Timliews,thx它非常有效!请随意添加以下完整的解决方案;避免将其编辑到问题中,因为这不适用于Stackoverflow的问答格式:)