Answer the question
In order to leave comments, you need to log in
How to organize a many-to-many relationship in Yii2?
There are two tables: films - a table with films, categories - a table with categories, films_categories - a link between the films and categories tables. So, how do I organize a connection in Yii2? Let's say you want to get all movies from a certain category, or get all categories for a certain movie. Help, I used only the simplest connections before (hasOne, hasMany).
Answer the question
In order to leave comments, you need to log in
Here's how it's done:
class FilmCategory {.....
public function getFilms(){
return $this->hasMany(Films::className(), ['film_id' => 'film_id'])
->viaTable('films_categories', ['category_id' => 'category_id']);
}
So have you tried it?
// join with multiple relations
// find the orders that contain books and were placed by customers who registered within the past 24 hours
$orders = Order::find()->innerJoinWith([
'books',
'customer' => function ($query) {
$query->where('customer.created_at > ' . (time() - 24 * 3600));
}
])->all();
// join with sub-relations: join with books and books' authors
$orders = Order::find()->joinWith('books.author')->all();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question