我清楚了解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();
});
答案 0 :(得分: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模型都会防止批量分配。
鉴于您从数据库中正确调用,这应该可以。
答案 1 :(得分:0)
如@Maraboc在评论部分中所建议,使用内容创建一个user
函数
public function user(){
$this->belongsTo(User::class);
}
这解决了我的问题