调用未定义的方法 Illuminate\Database\Query\Builder::vehicles()

Call to undefined method Illuminate\Database\Query\Builder::vehicles()

我有两个模型。 一个“车辆”和一个“租户”。

他们之间有以下关系。

A Tenant hasMany vehicles. A vehicle belongsTo a single Tenant.

对于Tenant.php:

public function vehicles()
{
    return $this->hasMany('\App\Models\Vehicle');
}

对于Vehicle.php:

public function tenant()
{
    return $this->belongsTo('\App\Models\Tenant');
}

正在执行:

 $this->user = $request->user();
    $userTenant = $this->user->tenant();
    $vehicle= $userTenant->vehicles()->first();

导致错误

Call to undefined method Illuminate\Database\Query\Builder::vehicles()

指向这一行:

$vehicle= $userTenant->vehicles()->first();

我不太确定为什么会这样=\

我看不出你的post和User有什么关系,但是tenant()(带括号)可能是returns和BelongsTo 或分配给 $userTenant 的其他 Relation 个实例。尝试将该行更改为 tenant 之后不带括号的版本,以获取租户模型实例:

$userTenant = $this->user->tenant;

根据评论更新

当您调用关系作为方法时,例如

$myModel->relation()

得到对应关系class。当用作 getter 时,例如

$myModel->relation

本质上和调用是一样的

$myModel->relation()->get() 用于针对多个模型的关系,或调用

$myModel->relation()->first() 用于针对单个模型的关系。

查看文档以获取有关 relationship methods vs. dynamic properties

的更多信息