【问题标题】:Laravel Eloquent HasManyThrough relationshipLaravel Eloquent HasManyThrough 关系
【发布时间】: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


【解决方案1】:

您不应该为此使用 hasManyThrough,因为 UserLocations 已经包含 location_id。在您的用户模型中,使用 hasManyRelationshipUserLocation

public function locations()
{
  return $this->hasMany(UserLocation::class, 'user_id');
}

然后要包含位置信息,只需急切加载它。

 $user = User::with(['locations.location'])->where('id', Auth::user()->id)->first();

【讨论】:

    猜你喜欢
    • 2016-09-26
    • 2019-03-26
    • 2015-07-27
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 2018-10-18
    相关资源
    最近更新 更多