warpig's avatar
Level 12

Cardinality violation: 1241 Operand should contain 1 column(s)

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
    )
  )
0 likes
4 replies
Talinon's avatar

@warpig

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();
warpig's avatar
Level 12

@Talinon it returns the following message:

Attempt to read property "image" on true
"<img src="{{ Storage::url($last->image) }}" alt="{{ $last->title }}"

however, i found out the duplication problem was because of this variable. i wasn't returning the relationship but since adding the relationship, debugbar isn't showing duplicates

        $popularPosts = Post::postedWithinDays(30)
            ->latest()
            ->take(2)
            ->skip(4)
            ->get();
Talinon's avatar

That's a completely different problem. Where did you mention anything about images in your original post?

warpig's avatar
Level 12

@Talinon the problem originated because i found out i had duplicate query, which at the time, i believed it had to do with the variables i wanted to refactor. but then i discovered i was not loading the "category" relationship. case closed.

Please or to participate in this conversation.