Answer the question
In order to leave comments, you need to log in
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
Use one of the plugins:
https://dimsemenov.com/plugins/magnific-popup/docu...
https://www.jacklmoore.com/colorbox/
Lightbox can help. Or you can write a popup window with the desired picture.
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question