Laravel 5.4雄辩的一对多关系

问题描述 投票:0回答:2

我很清楚我对Laravel雄辩关系的了解。不幸的是,我无法解决/找到一对多关系的问题。有人有任何想法/建议我的代码有什么问题吗?

怎么了

Eloquent没有从手机表中找到任何相关数据。 Current result (pastebin)

应该怎么做

从移动表中获取所有相关数据。

涉及的代码

我正在进行干净的Laravel 5.4安装。这是我创建/添加的唯一代码。

用户模型

public function phone(){

    return $this->hasMany('App\Mobile', 'user_id', 'id');

}

有了这个功能,eloquent会从移动表中获取列user_id == id的所有记录吗?

用户表

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

移动表

 Schema::create('mobiles', function (Blueprint $table) {
        $table->increments('id');

        $table->integer('user_id');

        $table->string('phoneNumber');

        $table->timestamps();
    });
laravel-5 eloquent
2个回答
0
投票

根据您的代码,我认为问题出在您的模型中。它应该如下:

用户表

protected $fillable=['name', 'email' , 'password'];

public function Mobile(){

    return $this->hasMany(Mobile::class);

}

移动表

protected $fillable=['user_id', 'phonenumber'];

public function User(){

    return $this->hasMany(User::class);

}

您需要在模型上指定可填充或受保护的属性,因为默认情况下所有Eloquent模型都会防止批量分配。

鉴于您从数据库正确调用,这应该工作。


0
投票

正如@Maraboc在评论部分中所建议的那样,使用内容创建一个user函数

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

这解决了我的问题

© www.soinside.com 2019 - 2024. All rights reserved.