duanlv2788 2017-05-11 11:51
浏览 118
已采纳

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

I have two models. A "Vehicle" and a "Tenant".

They have following relationships with each other.

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

For Tenant.php:

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

For Vehicle.php:

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

Executing this :

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

results in an error

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

Pointing to this line :

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

I am not so sure why is this happening =\

  • 写回答

1条回答 默认 最新

  • doujiu3882 2017-05-11 11:55
    关注

    I can't see from your post what the relations are with a User, but the tenant() (with parentheses) probably returns a BelongsTo or other Relation instance that is being assigned to $userTenant. Try changing that line to a version without parentheses after tenant to get the Tenant Model instance instead:

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

    Update from comments

    when you call a relation as method, e.g.

    $myModel->relation()

    you get the corresponding relation class. When used as a getter, e.g.

    $myModel->relation

    it's essentially the same thing as calling

    $myModel->relation()->get() for relations that target multiple models, or calling

    $myModel->relation()->first() for relations that target a single model.

    Checkout the docs for more info on relationship methods vs. dynamic properties

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?