Laravel 获取属于列的数据

Laravel get data with belongsto column

计划 table 列 编号、名称、类型

个客户 table 列 身份证号,姓名,plan_id

// for client

function plan(){
    return $this->belongsTo(Plan::class, 'plan_id', 'id');
}

我输入plan_id给客户table

我想从客户 table 那里获取这些客户数据 if plan type ='PP'

$clientData = Client::with(['plan' => function ($clientData) {
    $clientData->where('type', 'PP');
})->get();

我试过了,但我从客户那里得到了所有数据 table。

->with() 不限制初始查询的数据,它只是急于加载它。您需要为此使用 ->whereHas()

$clientData = Client::with(["plan"])
->whereHas("plan", function ($query) {
    $query->where("type", "=", "PP");
})->get();

这只会 return Client 具有 Plan 类型 PP 的记录。