You want to get the latest two records, with the hasMany Category relationship?
I think you can simplify this to something like:
[$postOne, $postTwo] = Post::with('category')->latest()->take(2)->get();
I used to have this in my WelcomeController when I wanted to return the last post created on the posts table ($post) and the second latest record ($postTwo), both queries were expected to come with the "category" method (a one to many relationship) but since i want to avoid repeating the relationship on the query, i tried to refactor it
$post = Post::with('category')->latest()->take(1)->get();
$postTwo = Post::with('category')
->latest()
->take(1)
->skip(1)
->get();
$post = Post::with('category')
->where(function($query) use ($post) {
$query->where('created_at', '=', $post->latest()->take(1));
})
->orWhere(function($query) use ($post) {
$query->where('created_at', '=', $post->latest()->take(1))->skip(1);
})->get();
From what i've read the error is based on the fact that i am looking to return multiple values but one is expected or "allowed." i thought that by using take(1) i would be solving the issue, however when i look at the query, it selects all posts: "select * from posts" so what am i doing wrong?
im only looking to return 1 post for each of the where's.
SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s)
select
*
from
`posts`
where
(
`created_at` = (
select
*
from
`posts`
order by
`created_at` desc
limit
1
)
)
or (
`created_at` = (
select
*
from
`posts`
order by
`created_at` desc
limit
1
)
)
Please or to participate in this conversation.