简体   繁体   中英

eager loading return null on one to many relationship

i have three table which have sort of many to many relationship the table name: notes(id,user_id,card_id,body), Users(id,name,password,...), Card(id,cardname,cardText) now i want to use eager loading to get the related user name i have three model which represented like here:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Card extends Model
{
    /*public $table= 'Fake';*/
    public $timestamps = false;
    public function notes()
    {
        return $this->hasMany(Note::class);
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Note extends Model
{

    public $timestamps = false;
    public function cards()
    {
        return $this->belongsTo(Card::class);
    }

    public function users()
    {
        return $this->belongsTo(User::class);
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public $timestamps = false;
    public function notes()
    {
        return $this->hasMany(Note::class);
    }

}

and in my route i used following:

<?php

use App\Card;
Route::get('/', function () {
    $card=new Card();
    $card->id=1;
    $card->load('notes.users')->all();
    return $card;
});

but i don't know why i get null in user in json: the json file:

{
id: 1,
notes: [
{
id: 1,
card_id: 1,
user_id: 1,
body: "Hussein Jafari",
users: null
},
{
id: 2,
card_id: 1,
user_id: 1,
body: "Ammpeaa",
users: null
},
{
id: 12,
card_id: 1,
user_id: 1,
body: "KAIRIMI SANJABI",
users: null
},
{
id: 13,
card_id: 1,
user_id: 1,
body: "MOAHAHS KASK KSK",
users: null
},
{
id: 14,
card_id: 1,
user_id: 1,
body: "bENAJAJ KSAK KS",
users: null
}
]
}

You can change your relation in Note class as:

public function users()
{
    return $this->belongsTo(User::class, 'user_id', id);
}

It is because eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id .

But in your case, it was looking for users_id column.

OR

You can change the relation name as:

public function user()
{
    return $this->belongsTo(User::class);
}

Then eager load as:

$card->load('notes.user')->all();

Docs

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