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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?