desancheztorres
desancheztorres

Reputation: 353

Laravel eloquent get data from two tables

Laravel Eloquent Query builder problem

Hello I have a problem when I am trying to get all the rows where slug = $slug.

I will explain in more details:

I have two tables, cards and card_categories.

cards has category_id.
card_categories has slug.

What I need is a query which returns all the cards which contents the slugs.

For example I made this:

$cards = Card::leftJoin('card_categories', 'cards.id', '=', 'card_categories.id')
        ->select('cards.*', 'card_categories.*')
        ->where('card_categories.slug', $slug)
        ->paginate(5);

But what happens is that just return 1 row per category.

I don't know what is wrong.

Many thanks.

Upvotes: 1

Views: 7372

Answers (1)

George Hanson
George Hanson

Reputation: 3030

I think I understand what you mean, from your explanation I would imagine your card model is as follows.

class Card extends Model {
    protected $table = 'cards';

    public function category()
    {
        return $this->belongsTo(Category::class)
    }
}

In which case, you should just be able to do this:

$cards = Card::whereHas('category', function ($query) use ($slug) {
    $query->where('slug', $slug);
})->paginate(5);

That will select all of the cards that has the category id of the given slug.

Upvotes: 1

Related Questions