模型获取GrandParent

时间:2019-05-14 17:18:48

标签: laravel

我的应用程序中具有以下模型:

  1. 驾驶室
  2. 目的地
  3. 旅客

位置:

  • 出租车有很多目的地
  • 出租车有很多乘客
  • 目的地有很多出租车
  • 目的地有很多乘客
  • 乘客有一辆出租车
  • 乘客有一个目的地

现在,我试图运行一个查询,该查询返回所有出租车的列表以及目的地,前往每个目的地的乘客数量以及车内乘客总数:

Cab::withCount(["passengers" => function($q) {
    return $query->whereNull("expired_at");
}])
->when($withDestinations, function ($query) use ($status) {
    return $query->whereHas("destinations")
        ->with(["destinations" => function ($query) {
            return $query->whereHas("passengers", function ($query) {
                return $query->whereNull("expired_at");
            })->withCount("passengers");
        }]);
})
->paginate(25)

现在,这里的问题是由于某种原因,它使乘客返回目的地,但没有按cab_id过滤查询。

这些是我的模特:

cab.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Cab extends Model
{
    use SoftDeletes;

    protected $dates = ["arrived_at", "departed_at", "suspended_at", "deleted_at"];

    public function company() {
        return $this->belongsTo("App\Models\Company", "company_id");
    }

    public function driver() {
        return $this->belongsTo("App\Models\Driver", "driver_id");
    }

    public function status() {
        return $this->belongsTo("App\Models\Status", "status_id");
    }

    public function destinations() {
        return $this->belongsToMany("App\Models\Destination", 'destination_cab', 'cab_id', 'destination_id');
    }

    public function passengers() {
        return $this->hasMany("App\Models\Passenger", "cab_id");
    }

    public function photo() {
        return $this->belongsTo("App\Models\Resource", "photo_id");
    }
}

destination.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Destination extends Model
{
    use SoftDeletes;

    protected $dates = ["suspended_at", "deleted_at"];

    public function company() {
        return $this->belongsTo("App\Models\Company", "company_id");
    }

    public function cabs() {
        return $this->belongsToMany("App\Models\Cab", "destination_cab", "destination_id", "cab_id");
    }

    public function passengers() {
        return $this->hasMany("App\Models\Passenger", "destination_id");
    }
}

passenger.php

<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class Passenger extends Model
{

    protected $dates = ["due_at", "expired_at"];

    protected $casts = ["meta" => "json"];

    protected $fillable = ["meta"];

}

0 个答案:

没有答案