【问题标题】:eager loading return null on one to many relationship急切加载在一对多关系上返回 null
【发布时间】:2016-11-16 09:27:18
【问题描述】:

我有三个表,它们具有多对多的关系 表名:notes(id,user_id,card_id,body), Users(id,name,password,...), Card(id,cardname,cardText) 现在我想使用渴望加载来获取相关的用户名 我有三个模型,如下所示:

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

}

在我的路线中,我使用了以下内容:

<?php

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

但我不知道为什么我在 json 中的 user 中为 null: json文件:

{
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
}
]
}

【问题讨论】:

    标签: php mysql laravel eloquent laravel-5.2


    【解决方案1】:

    您可以将Note 类中的关系更改为:

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

    这是因为 eloquent 通过检查关系方法的名称并在方法名称后加上_id 来确定默认的外键名称。

    但在您的情况下,它正在寻找 users_id 列。

    您可以将关系名称更改为:

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

    然后急切加载为:

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

    Docs

    【讨论】:

    • 感谢重播,我做到了,但我仍然像上面的 json 一样将用户设为 null。不一样
    • 然后确保您的数据库中有id 1 的用户。
    • db 中的用户 id 是 1,2,3 并且它们都在 notes 表中有记录但是为什么你说用户 ID 为 1 我们没有在查询中提到用户我们只想要用户id为一的注册卡及其相关说明
    • 通过查看您的 JSON 文件,尤其是 notes 节点中的 user_id,以确保 DB 中有相关用户。
    猜你喜欢
    • 2021-12-01
    • 2020-10-23
    • 2020-09-12
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    相关资源
    最近更新 更多