Laravel关系2层

时间:2015-12-01 14:28:10

标签: php laravel eloquent relationship

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

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);
    }
}

现在我在User类中使用此代码:

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

它不起作用,因为我需要将它作为关系方法,但with方法返回查询构建器。

在决赛中我必须致电$user->games并且它应该返回用户链接到的所有游戏。

1 个答案:

答案 0 :(得分:0)

好。我想我现在明白了。

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

你可以试试这个:

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

这将获取用户并急切加载所有关系。因为Place属于一个游戏,而游戏又属于Lot,你可以这样做:

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

此外,地方实际上是一个数据透视表,您可以利用Eloquent的many-to-many关系,我建议您阅读。