Hi. I’m fiddling around with Yii2 and I need some help with this query. I have 2 tables; Article and Image. What I would like to achieve is select all from table Article with table Images but limit to 1 image only. Schema as per below:-
Article
----------
- id
- title
- post
Image
----------
- id
- article_id
- thumbnail
- path
Here is my relations:-
models/Image.php
public function getArticle()
{
return $this->hasOne(Article::className(), ['id' => 'article_id']);
}
models/Article.php
public function getImages()
{
return $this->hasMany(Image::className(), ['article_id' => 'id']);
}
Hi, just got got yii2-debug up and running. Below is the database queries executed:-
SHOW FULL COLUMNS FROM `article`
SHOW FULL COLUMNS FROM `image`
SELECT * FROM `article` WHERE article.1 = :1 LIMIT 5 OFFSET 85
SELECT COUNT(*) FROM `article` WHERE article.1 = :1
SHOW CREATE TABLE `article`
SELECT * FROM `image` WHERE (image.status = 1) AND (`article_id` IN ('86', '87', '88', '89', '90')) ORDER BY `created` DESC LIMIT 1
SHOW CREATE TABLE `image`
Hi. I have tried your suggested method. One problem through; it does not limit one image to one article IF an article has more than one image. Is there a way to set LIMIT in relation?
I’ve google-ed around a little bit and found that using GROUP BY SQL query should help. Referenced from here. Here’s my code so far.