簡體   English   中英

關系在Laravel中不起作用

[英]Relationship doesnt work in Laravel

在我的用戶模型中,我有2個關系

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

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

我使用時第二個城市不起作用

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

例如。 它給出了信息

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

階級城市是

<?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();
 }

 }

問題是什么? 為什么一種關系有效而另一種無效。

將代碼$this->belongsTo(City::class, 'city_id')視為hasOne關系的反函數,該關系最終將查看“用戶所屬”的城市?

這是該關系結構的預期目的嗎? 如果與它相反,則我們正在尋找“屬於用戶”的城市,我們應該使用$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()調用應該在find()first()findOrFailfirstOrFail()get()

這應該是您渴望向User加載City所需的全部。

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

但是,如果需要在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