Laravel 5 belong不返回所需的结果
我希望Laravel 5 belong不返回所需的结果,laravel-5,Laravel 5,我希望用户只能拥有一个发行版(葡萄牙语的意思是地区)。发行版可以有多个用户。这是一个相当简单的关系,但当您有第三个名为distritos的表时,问题就来了,它唯一的任务就是将数字转换为字符串(我不知道这类表的名称) 分发表 $table->increments('id'); $table->string('distrito'); e、 g 用户表 $table->string('name'); $table->string('last_name'); $table-&g
用户
只能拥有一个发行版
(葡萄牙语的意思是地区
)。发行版可以有多个用户
。这是一个相当简单的关系,但当您有第三个名为distritos
的表时,问题就来了,它唯一的任务就是将数字转换为字符串(我不知道这类表的名称)
分发表
$table->increments('id');
$table->string('distrito');
e、 g
用户表
$table->string('name');
$table->string('last_name');
$table->string('profile_picture')->default('default.jpg');
$table->string('userProfile')->default('');
$table->float('stars')->default(0);
distrito_用户表此表将引用用户居住的位置
$table->integer('user_id'); //id of the user
$table->integer('distrito_id'); //Id of the district where the user lives
用户型号
public function distritoUtilizador(){
return $this->belongsTo(DistritoUser::class);
}
protected $table = 'distrito_user';
$user = Auth::user();
dd($user->distritoUtilizador);
发行商用户模型
public function distritoUtilizador(){
return $this->belongsTo(DistritoUser::class);
}
protected $table = 'distrito_user';
$user = Auth::user();
dd($user->distritoUtilizador);
呼唤雄辩的模型
public function distritoUtilizador(){
return $this->belongsTo(DistritoUser::class);
}
protected $table = 'distrito_user';
$user = Auth::user();
dd($user->distritoUtilizador);
它返回null
第一个问题:这是解决我的问题的正确方法吗(用户住在某个地方,我需要填充该位置)
如果这是解决我的问题的正确方法:为什么它没有返回所需的结果?对于简单的一对多,只需将外键存储到用户模型上的distrito,不需要中间表
$table->increments('id')->unsigned();
$table->string('name');
$table->string('last_name');
$table->string('profile_picture')->default('default.jpg');
$table->string('userProfile')->default('');
$table->float('stars')->default(0);
$table->integer('distrito_id')->unsigned();
$table->foreign('distrito_id')->references('id')->on('distrito');
并完全删除distrito_用户表。现在使用此方法:
public function distrito(){
return $this->belongsTo(Distrito::class, 'id');
}
而distrito有:
public function users(){
return $this->hasMany(User::class);
}
同时将distrito迁移更改为:
$table->increments('id')->unsigned();
一切都很奇妙,但只需对您的问题进行快速编辑:return$this->belongsTo(Distrito::class)
应该是返回$this->belongsTo(Distrito::class,'id')代码>。我不知道为什么,但是如果没有'id'
,它就不能工作。我会在一个小时内测试更多,但乍一看,它的工作奇迹。谢谢你也很好,听到了吗,你是否通过更改在Distrito模型上指定了与id不同的主键?没有。我的表如问题所述,模型没有任何修改。只要让有很多。这有点奇怪,为什么没有'id'
它就不能工作。奇怪的是,如果在创建迁移和建立模型关系时遵循常规约定,Elotent应该能够基于模型名称解析主键。无论如何,很高兴它能为您工作。它仍然返回空值。返回$this->belongsTo(Distrito::class,'id')代码>有时返回正确的值。其他时候,它无法返回值。