How do I work with many-to-many relations in Yii2
When using a junction table for many-to-many relations, you have to
- Define the relations
- Link the two models together
In the User model define the following relation function:
public function getMarkets() {
return $this->hasMany(Market::className(), ['id' => 'market_id'])
->viaTable('tbl_user_market', ['user_id' => 'id']);
}
In the Market model define the following relation function:
public function getUsers() {
return $this->hasMany(User::className(), ['id' => 'user_id'])
->viaTable('tbl_user_market', ['market_id' => 'id']);
}
And finally, after saving both models, link them together:
$user = new User;
$user->name = 'Foo';
$user->save();
$market = new Market;
$market->name = 'Bar';
$market->save();
$user->link('markets', $market);
The call to link()
will populate the junction table.
Reference: http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#link()-detail
Many To Many relations Yii2
It's bad way because the making of that code in multiple models will make models dirtier. The better way is usage of a universal component that can manage relations in your models. For example yii2-many-to-many-behavior
Yii2 many-to-many model relation
This public $images;
property should be renamed because it coincides with the name of relation getImages()
class Slider extends Sl
{
const SCENARIO_CREATE = 'create';
const SCENARIO_VIEW = 'view';
const SCENARIO_UPDATE = 'update';
public $images; // This should be renamed
...
YII2 how do i handle many to many relationships?
Method getCategories() returns ActiveQuery object instead of models. If you need to get an array of category models you must use magical property categories
. For example:
var_dump($user->categories);
Many-to-many relation in yii2 activedataprovider
You can create two more relations like this
In category:
public function getProducts()
{
return $this->hasMany(Product::className(), ['id' => 'product_id'])->via("productCategories");
}
And in product:
public function getCategories()
{
return $this->hasMany(Category::ClassName(), ['id' => 'category_id'])->via("productCategories");
}
Then you can use it like this
$cats = Category::findOne(['slug1'=>$slug1]);
$dataProvider = new ActiveDataProvider([
'query' => $query = $cats->getProducts(),
'sort'=>array(
'defaultOrder'=>['id' => SORT_ASC],
),
'pagination' => [
'pageSize' => 9,
],
]);
Yii 2 Filter many-to-many relation on a value in the junction table
I found in the documentation that you can add a callback to the viaTable() function that can be used to customize the join query. You can use it like this:
public function getAcceptedMembers() {
return $this->hasMany(Member::className(), ['id' => 'member_id'])->viaTable('EventMemberConnection acceptedConnection', ['event_id' => 'id'], function($query){
$query->where(['acceptedConnection.accepted' => 1]);
});
}
Related Topics
Multiple Auto Increment in MySQL
Utf8 Filenames in PHP and Different Unicode Encodings
Is This a PHP Date() Bug, or Is There Something Wrong with My Code
How to Properly Display Chinese Characters in PHP
How to Force Formrequest Return JSON in Laravel 5.1
Cannot Pass Null Argument When Using Type Hinting
Generating a Waveform Using Ffmpeg
Find Out Where Your PHP Code Is Slowing Down (Performance Issue)
How to Display Woocommerce Category Image
Fatal Error: Call to Undefined Function Mcrypt_Encrypt()
Cannot Call Function SQLsrv_Connect()
PHP File Uploads Doesnot Read $_Files['Image']
Get Code Line and File That's Executing the Current Function in PHP