Laravel关系2层

Laravel relationship 2 layers

我的数据库(=模型)结构如下:

game:  
    lot (typeof Lot)
    places (array type of Place)
         place_id // just a number of a lot in some game
         user_id

这样到处打电话怎么办:

User::find(1)->games() // returns Game collection where user has places

?

型号是:

class Place extends Model
{
    protected $fillable = ['place_id', 'user_id', 'game_id'];

    public function user() {
        return $this->belongsTo(User::class);
    }

    public function game() {
        return $this->belongsTo(Game::class);
    }
}

用户:

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'steam_id', 'avatar'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['remember_token'];

    /**
     * Get all of the tasks for the user.
     */
    public function items()
    {
        return $this->hasMany(SteamItem::class);
    }

    public function places() {
        return $this->hasMany(Place::class);
    }
}

游戏:

class Game extends Model
{
    protected $fillable = ['lot_id'];

    public function lot() {
        return $this->belongsTo(Lot::class);
    }

    public function places() {
        return $this->hasMany(Place::class);
    }
}

现在我在我的用户 class 中使用此代码:

public function games() {
    return Game::with(['places' => function ($query) {
        $query->where('user_id', $this->id);
    }]);;
}

它不起作用,因为我需要将其作为一种关系方法,但是 with 方法 return 是一个查询构建器。

在决赛中我必须调用 $user->games 它应该 return 我所有的游戏用户链接到地方。

好的。我想我现在明白了。

用户有很多地方。地方属于用户。 地方属于游戏。游戏有很多地方。

你可以试试这个:

$user = User::with('places.game.lot')->find(1);

这将获取用户并预先加载所有关系。因为 Place 属于游戏,而游戏又属于 Lot,所以您可以这样做:

@foreach ($user->places as $place)
    <img src="{{$place->game->lot->imageUrl}}" />
@endforeach

此外,place 实际上是一个支点 table,您可以利用 Eloquent 的 many-to-many 关系,我建议您阅读一下。