То, что вы делаете, это использование QueryBuilder вместо Eloquent.В файле модели Serie
вы должны определить функцию для доступа к отношению Genre
.
Из того, что я понимаю из вашего кода, у вас есть отношение многие ко многим между жанром и серией.
Я предполагаю, что первичные ключи для Serie
и Genre
имеют имена id
, а внешние ключи в SerieGenre
имеют имена Genre_id
и Serie_id
соответственно в зависимости от вашего кода.
// App\Serie.php
public function series_genres()
{
// hasMany($related, $foreign_key, $local key)
// if you don't specify the $foreign_key, Laravel will assume it's named 'serie_id' based on its conventions.
// if you don't specify the $local_key, Laravel will assume it's named 'id' which is the case so we don't need to specify
return $this->hasMany('App\SerieGenre', 'Serie_id');
}
public function genres()
{
// belongsToMany($related, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relation)
// if you don't specify the $table, Laravel will assume it's named 'serie_genre' based on its conventions.
// if you don't specify the $foreignPivotKey, Laravel will assume it's named 'serie_id' based on its conventions.
// if you don't specify the $relatedPivotKey, Laravel will assume it's named 'genre_id' based on its conventions.
// if you don't specify the $parentKey, Laravel will assume it's named 'id' which is the case so we don't need to specify
// if you don't specify the $local_key, Laravel will assume it's named 'id' which is the case so we don't need to specify
// You don't need to worry about the $related variable
return $this->belongsToMany('App\SerieGenre','SeriesGenres', 'Serie_id', 'Genre_id');
}
Если вы хотите получить доступ к модели Serie или Genre из сводной таблицы, вам следует также определить следующие функции.
// App\SerieGenre.php
public function serie()
{
// belongsTo($related, $foreignKey, $ownerKey, $relation)
// if you don't specify the $foreign_key, Laravel will assume it's named 'serie_id' based on its conventions.
// if you don't specify the $local_key, Laravel will assume it's named 'id' which is the case so we don't need to specify
// you don't need to worry about the $relation variable
return $this->belongsTo('App\Serie', 'Serie_id');
}
public function genre()
{
return $this->belongsTo('App\Genre', 'Genre_id');
}
И, наконец, если вы хотите получить доступ к отношениям Serie из модели жанра, это то же самое.
// App\Genre.php
public function series_genres()
{
return $this->hasMany('App\SerieGenre', 'Genre_id');
}
public function series()
{
return $this->belongsToMany('App\SerieGenre','SeriesGenres', 'Genre_id', 'Serie_id');
}
Обычно вам не нужно передавать более одного параметрак функциям отношений, но это верно только в том случае, если вы следуете методу написания laravel (единственное число StudlyCase для моделей, множественное число snake_case для имен таблиц, id в качестве первичного ключа и имя модели snake_case'd + _id для внешних ключей)
Наконец, вам нужно спросить себя, хотите ли вы только детали взаимоотношений или вам также нужна сама модель.
В этом примере Serie с id = 2 относится к жанру с id = 4 (среди прочих) Serie::find(2)->genres()
будет производить следующий объект
Illuminate\Database\Eloquent\Collection {
all: [
App\Genre {
id: 4,
name: 'name',
...,
pivot: Illuminate\Database\Eloquent\Relations\Pivot {
Genre_id: 4,
Serie_id: 2,
...,
},
},
App\Genre {...},
App\Genre {...},
],
}
Serie::with('genres')->find(2)
будет производитьследующий объект
App\Serie {
id: 2,
Genres: Illuminate\Database\Eloquent\Collection {
all: [
App\Genre {
id: 4,
name: 'name'
...,
pivot: Illuminate\Database\Eloquent\Relations\Pivot {
Genre_id: 4,
Serie_id: 2,
...,
},
},
App\Genre {...},
App\Genre {...},
App\Genre {...},
App\Genre {...},
],
},
Я предлагаю вам прочитать документацию, потому что эта тема лучше объяснена там.