Z
Z
zidevar2016-11-19 17:22:18
Yii
zidevar, 2016-11-19 17:22:18

Yii2. Best practice for implementing a many-to-many relationship?

There was a need to implement a many-to-many relationship. There are many options. Maybe there is some best practice for this task? I considered the option https://github.com/voskobovich/yii2-many-to-many-b... but they use a linking method different from that appeared in yii2 - link($relationName, relatedModel, $extraColumns = []) .
Let's say there are Post and Tag. There is also PostTag, respectively. I understand correctly that the right decision would be to put into the behavior the method in which links are established using link($relationName, relatedModel, $extraColumns = []), wrapped in a transaction? Is there an example of such an implementation? I didn't find.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Fedorov, 2016-11-21
@zidevar

As far as I understand, your question is about saving related data. In my opinion, the use of link is quite appropriate for linking a pair of records, but for linking multiple records to one (as in your example), you should not use it, because this leads to the growth of the code and, accordingly, its complication. In my opinion, it is better to use the behavior you provided. it does almost everything you described (including transactions)

M
Maxim Timofeev, 2016-11-19
@webinar

best practice are standard framework solutions, for example:

public function getReviews()
{
    return $this->hasMany(Review::className(), ['id' => 'review_id']);
}

such connections are well documented and it is not entirely clear why they do not suit you?
Perhaps you have a specific problem that you do not know how to solve? Then describe in more detail.
The option by reference is the behavior for the model. In essence, an attempt to bring frequently used methods into behavior and simplify their use. But at the same time, attempts to universalize this class have led to a loss of performance in some places. In my opinion, the approach with behaviors is sound, but you need to write your own behaviors for the project and I see no reason to make connections in them.

S
Sergey Zhubartovich, 2017-02-24
@patrickj

<div class="box">
  <img src="iphone.png" alt="">
</div>
<div class="next-box"></div>

.box {
  overflow: hidden;
}

.box img {
  position: absolute;
  top: 100%; 
  left: 50%;
  transform: translate(-50%, -50%);
}
.next-box {
  position: relative;
}

.next-box:before {
  content: "";
  display: block;
  width: 60px;
  height: 60px;
  background: #28c8c6 url(down-icon.png) no-repeat  20px 10px;
  border-radius: 100%; 
  position: absolute
  top: -30px;
  left: 50%;
  transform: translateX(-50%);
}

Something like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question