Использование Model в методе join () - PullRequest
0 голосов
/ 05 апреля 2019

Можно ли использовать имя модели в join() в качестве параметра вместо имени таблицы.

Ex. Имя таблицы базы данных: 'SeriesGenres' , но название модели 'SerieGenre' .

public function showContent($id){
        $serie = Serie::findOrFail($id);

        // SELECT Genres.name
        // FROM Genres INNER JOIN SeriesGenres ON Genres.id = SeriesGenres.Genre_id
        // WHERE SeriesGenres.Serie_id = $serie

        $getGenreNamesById = Genre::select('name')
                   ->join('SeriesGenres', 'SeriesGenres.Genre_id', '=', 'Genres.id')
                   ->whereIn('Serie_id',$serie)->get();
}

Хотите сделать что-то вроде этого:

$serieGenre =SerieGenre::all();
$getGenreNamesById = Genre::select('name')
                   ->join($serieGenre, 'Genre_id', '=', 'Genres.id')
                   ->whereIn('Serie_id',$serie)->get();

Ответы [ 2 ]

0 голосов
/ 05 апреля 2019

То, что вы делаете, это использование 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 {...},
    ],
},

Я предлагаю вам прочитать документацию, потому что эта тема лучше объяснена там.

0 голосов
/ 05 апреля 2019

Вы можете попробовать получить доступ к имени таблицы следующим образом:

(new SerieGenre)->getTable();

Будет возвращено имя таблицы.

Так будет как:

$serieGenre =SerieGenre::all();
$getGenreNamesById = Genre::select('name')
                   ->join((new SerieGenre)->getTable(), 'Genre_id', '=', 'Genres.id')
                   ->whereIn('Serie_id',$serie)->get();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...