vbnewbie
vbnewbie

Reputation: 226

Laravel: How to query data from multiple table?

The db have 3 tables chars, tags, and chars_tags

chars has the following columns:

id | char_name

tags has the following columns:

id | tag_name

chars_tags has the following columns:

id | char_id | tag_id

I always use the code below to get the data, because last time the char table has another column called 'tag_id', now they remove the 'tag_id' column and change it to pivot table which is 'chars_tags'

$char = chars::where('id', '=', 1)
     ->with('tags:id,tag_name')
     ->get();

So how can I get the char with tag now?

Upvotes: 2

Views: 76

Answers (2)

M Khalid Junaid
M Khalid Junaid

Reputation: 64496

First set up your models using a many to many relationship between chars and tags

class Char extends Model
{
    public function tags()
    {
        return $this->belongsToMany(Tag::class, 'chars_tags', 'char_id');
    }
}

class Tag extends Model
{
    public function chars()
    {
        return $this->belongsToMany(Char::class, 'chars_tags', 'tag_id');
    }
}

Now you can eager load your related tags with chars

$char = Char::with('tags')
            ->where('id', '=', 1) 
            ->get(); 

or you could use find() if you need a single object

$char = Char::with('tags')->find(1); 

Upvotes: 2

Kévin Ferradj
Kévin Ferradj

Reputation: 956

You can also use sql joins: https://laravel.com/docs/5.6/queries#joins1

DB::table('chars')
->where('chars.id', 1)
->leftJoin('chars_tags', 'chars_tags.char_id', '=', 'chars.id')
->leftJoin('tags', 'tags.id', '=', 'chars_tags.tag_id')
->get();

Upvotes: 1

Related Questions