【发布时间】:2020-10-14 01:16:21
【问题描述】:
试图通过用户获取位置。目前我收到一个错误,所以要么我的 hasManyThrough 设置不正确,要么我的数据结构是。它仍然是一个新项目,所以我不介意重组数据库以使默认的 hasManyThrough 正常工作。
$user = User::with('locations')->find(Auth::user()->id);
echo '<pre>';
die(print_r($user->locations,true));
型号:
用户:
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
public function locations() {
return $this->hasManyThrough(
Location::class,
UserLocations::class,
);
}
}
用户位置
class UserLocations extends Model
{
protected $fillable = [
'user_id',
'location_id',
];
public function user()
{
return $this->belongsTo(User::class);
}
public function location()
{
return $this->belongsTo(Location::class);
}
}
地点
class Location extends Model
{
protected $fillable =
[
'city',
'name',
'timezone',
'email',
'state',
'address',
'address1',
'zip_code',
];
public function user_locations()
{
return $this->hasMany(UserLocations::class);
}
}
数据结构
Users:
-id
-name
-email
-password
UserLocations:
-id
-user_id
-location_id
Locations:
-id
-name
-city
【问题讨论】:
-
错误是什么?
标签: laravel eloquent relationship