У меня есть база данных (= модель) структура типа:Laravel отношения 2 слоя
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
, и он должен вернуть мне всех пользователей игр, подключенных к месту.
читать с функцией() http://laravel.com/docs/5.1/eloquent-relationships#eager-loading –
Да, я слышал об этом. Но, как я ее узнал, он будет работать только в моем контроллере, и я хочу реализовать его как отношения. Является ли это возможным? – Hiron123
Можете ли вы показать нам свои модели? –