简体   繁体   English

关系在Laravel中不起作用

[英]Relationship doesnt work in Laravel

In my User model i have 2 relationships 在我的用户模型中,我有2个关系

 public function role()
{
    return $this->belongsTo(Role::class, 'role_id');
}

public function city()
{
    return $this->belongsTo(City::class, 'city_id');
}

The second City doesnt work when i use 我使用时第二个城市不起作用

$user = App\User::findorfail(1)->with('city')->first(); 

for example. 例如。 It gives the message 它给出了信息

Illuminate/Database/Eloquent/RelationNotFoundException with message 'Call to undefined relationship [city] on model [App/User].

Class City is 阶级城市是

<?php
 namespace App;

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


 class City extends Model
 {
 use SoftDeletes;

 protected $fillable = ['name', 'nomos_id','user_id'];
 protected $table = 'cities';


 public function setNomosIdAttribute($input)
 {
    $this->attributes['nomos_id'] = $input ? $input : null;
 }

 public function nomos()
 {
    return $this->belongsTo(Nomoi::class, 'nomos_id')->withTrashed();
 }

 }

What is the problem? 问题是什么? Why one relationship works and the other doesnt. 为什么一种关系有效而另一种无效。

Looking at the code $this->belongsTo(City::class, 'city_id') as an inverse of hasOne relationship that eventually would be looking at a city that the "user belongs to"? 将代码$this->belongsTo(City::class, 'city_id')视为hasOne关系的反函数,该关系最终将查看“用户所属”的城市?

Is this the intended purpose of this relation structure? 这是该关系结构的预期目的吗? If it is the inverse of it where as, we are looking for a city that "belongs to the user" we should be using $this->hasOne(City::class, 'city_id') of $this->hasMany(City::class, 'city_id') if it's a one-to-many relation. 如果与它相反,则我们正在寻找“属于用户”的城市,我们应该使用$this->hasMany(City::class, 'city_id') $this->hasOne(City::class, 'city_id')$this->hasMany(City::class, 'city_id') $this->hasOne(City::class, 'city_id') $this->hasMany(City::class, 'city_id')如果是一对多关系。

with() calls should come before find() , first() , findOrFail , firstOrFail() , or get() with()调用应该在find()first()findOrFailfirstOrFail()get()

This should be all you need to eager load the City with the User . 这应该是您渴望向User加载City所需的全部。

$user = App\User::with('city')->findOrFail(1); 

But if you need to explicitly call first() on City then you should be using: 但是,如果需要在City上显式调用first() ,则应使用:

$user = App\User::with(['city'->function($query){ 
    return $query->first();
})->findOrFail(1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM