我很清楚我对Laravel雄辩关系的了解 . 不幸的是,我无法解决/找到一对多关系的问题 . 有人有任何想法/建议我的代码有什么问题吗?
What is happening
Eloquent没有从手机表中找到任何相关数据 . Current result (pastebin)
What should happen
从移动表中获取所有相关数据 .
涉及的代码
我正在进行干净的Laravel 5.4安装 . 这是我创建/添加的唯一代码 .
User model
public function phone(){
return $this->hasMany('App\Mobile', 'user_id', 'id');
}
使用此功能,eloquent将从移动表中获取列user_id == id的所有记录吗?
User table
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Mobile table
Schema::create('mobiles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('phoneNumber');
$table->timestamps();
});
2 回答
根据您的代码,我认为问题出在您的模型中 . 它应该如下:
User table
Mobile table
您需要在模型上指定可填充或受保护的属性,因为默认情况下所有Eloquent模型都会防止批量分配 .
鉴于您从数据库正确调用,这应该工作 .
正如@Maraboc在评论部分中所建议的那样,使用内容创建一个
user
函数这解决了我的问题