【发布时间】:2018-11-05 18:01:59
【问题描述】:
我有两个模型和一对一关系如下:
class Property extends Model
{
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
}
class User extends Authenticatable
{
public function property()
{
return $this->hasOne(Property::class, 'user_id');
}
}
当我想从 Property 访问 User 时,我在返回值中有两次用户数组:
$property = Property::where('id', $id)->first();
return response()->json([
'property' => $property,
'user' => $property->user
], 201);
输出:
{
"property":{
"id":1,
"name":"test",
"user":{
"id":1,
"name":"arash"
}
},
"user":{
"id":1,
"name":"arash"
}
}
这是怎么回事?为什么属性中有第一个用户?
【问题讨论】:
-
您能否展示一下 a) 如何查询
$propertyb)Property模型 -
问题已更新...检查
Property模型@devk的头等舱 -
您可能想要这样做:
['property' => $property, 'user' => $property->user()->first()]。$hidden属性也可以,但以后可能会导致一些无意的副作用
标签: laravel model relationship