I have a model Article
(id, title, content, created_at).
I can do:
$articles = Article::orderBy('created_at','DESC')->skip($start)->take($length)
->get(['id', 'title', 'content', 'created_at']);
But I want to get 2 random additional articles for each article . How can I do it?
For example:
{
{
id: 1,
title: 'title1'
content: 'qwqwqwqwqwqwqwq',
created_at: '2022-11-25 14:04:35',
related: {
id: 77,
title: 'title77'
content: 'fhhhfh',
created_at: '2022-11-26 17:04:57',
},
{
id: 15,
title: 'title15'
content: 'kkkkkkkk',
created_at: '2022-11-27 15:04:45',
},
},
...
}
2
Answers
Since
get()
method ofEloquent's Builder
returns acollection
(Check here), You can usemap()
method to add random items you mentioned.You can just simple assign the related articles in a loop:
If you want to load the related articles by relationship, you can create a column named
related_id
inarticle
table and set default value to1
Then, create a relationship on
Article
model:Then, you can load the related articles by using
with
function (remember to addrelated_id
to the array ofget
function):