简体   繁体   中英

Laravel 5.1 - BelongsTo relationship returns null

\App\User

class User

public function status() {

    return $this->belongsTo('App\UserStatus', 'user_status_id', 'id');
}

\App\UserStatus

class UserStatus

protected $fillable = ['id'];

public function user() {

    return $this->hasMany('App\User', 'user_status_id', 'id');
}

I already have the $user object from a simple User::find() query with some fields, then I try to access the status object by lazy loading it with $user->load('status') method.

I'm following the docs, but it seems useless since $user->status still returns null.

public function foo(User $user) {

    $user->load('status');
    $user->status // returns null
}

What am I doing wrong?

--------- SOLUTION ---------

Actually, to lazy load any relationship, the foreign key value needs to be stored in the model object.

In my find operation, I wasn't querying the user_status_id field. When I added this field into the query, the $user->status statement started to return the UserStatus model.

I don't think this information is written on the Laravel docs, it may be simple, but it took me some time to figure that out.

Actually, to lazy load any relationship, the foreign key value needs to be stored in the model object.

In my find operation, I wasn't querying the user_status_id field. When I added this field into the query, the $user->status statement started to return the UserStatus model.

I don't think this information is written on the Laravel docs, it may be simple, but it took me some time to figure that out.

in status() relation replace the line with

return $this->belongsTo('\App\UserStatus', 'user_status_id');

in user() relation with this

return $this->hasMany('\App\User', 'user_status_id');

Long story short add a '\' before App and remove third parameter since it is not many-to-many relationship.

Also make sure that you actually use Eloquent so add on top of models

namespace App;

use Illuminate\Database\Eloquent\Model;

class MODELNAME extends Model

and assign a table

protected $table = 'model_table';

I was using Psy Shell to run it. For the first argument in belongsTo(), that could just be Classname::class. I encountered the case that I cannot perform belongsTo(), but if you restart your Psy Shell, it worked. It is weird though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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