D
D
danildanil2017-10-23 11:40:07
css
danildanil, 2017-10-23 11:40:07

How to implement many-to-many in ActiveRecord?

Good afternoon.
With your permission 2 questions
1. In Active Record, an object instance is bound to a single row in a table. How then can one explain such methods, which are present in almost every implementation of AR, because they do not correspond to a record in the database?
Joins
$book = Book::all(array('joins' => array('author')));
sql => SELECT books.* FROM books INNER JOIN authors ON(books.author_id = authors.id)
Aggregate functions
Book::find('all', array('select' => 'avg(price) as avg_price, avg( tax) as avg_tax'));
sql => SELECT avg(price) as avg_price, avg(tax) as avg_tax FROM books LIMIT 5,10
Grouping
Book::all(array('group' => 'price')); sql =>
Book::all(array('group' => 'price', 'having' => 'price > 45.00'));
sql => SELECT * FROM books GROUP BY price HAVING price > 45.00
Or even a native query in the controller
$book = Book::find_by_sql('select title from books');
2. How can a many-to-many relationship be implemented in the simplest case? For example, I want to get all the tags from an article.
$article->tags;
If the relationship is one-to-many, then this is understandable. Approximately it will work like this:
$article->author;
We call Author::findOne(['author_id' => $author_id]); // Where is the author_id value in the article model class
Please explain. Thank you very much in advance.

Answer the question

In order to leave comments, you need to log in

6 answer(s)
A
Anton Usachov, 2019-07-24
@natali90

P
Pavel, 2019-07-24
@Asokr

Use one of the plugins:
https://dimsemenov.com/plugins/magnific-popup/docu...
https://www.jacklmoore.com/colorbox/

E
Evgenya-k2, 2019-07-24
@Evgenya-k2

Lightbox can help. Or you can write a popup window with the desired picture.

T
ThunderCat, 2019-07-24
@ThunderCat

fancy box?

D
Decadal, 2017-10-23
@danildanil

Have you noticed that the requests you describe are called through a static method, and not through an object?
AR static methods are like a query builder.
As for many-to-many:
$article->articleAuthor->authors - sequential implicit call to getArticleAuthor on the Article model, and getAuthors on the ArticleAuthor model There are
three models: Article, ArticleAuthor, Author, where ArticleAuthor is an intermediate table model and works with only two main ones fields: article_id, author_id.

V
Vlad, 2017-10-23
@DaFive

In the model and declare

public function getTags()
{
    return $this->hasMany(Tags:classname() (или какой у вас там класс тегов), ['article_id' => 'id']);
}

var_dump($article->tags);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question