2

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?

4
  • Have you add relationship in model ? Commented Jun 4, 2018 at 9:45
  • May be this will be help you Try this stackoverflow.com/a/42515792/3016038 Commented Jun 4, 2018 at 9:46
  • @DsRaj return $this->hasMany(tags::class, 'id', 'tag'); I only have this in my chars model Commented Jun 4, 2018 at 9:49
  • I think this is a Many to Many relationship (but you need to confirm about that: not enough behaviour in your quesiton) so you should follow: laravel.com/docs/5.6/eloquent-relationships#many-to-many and switch to belongsToMany() both in Char and Tag models... Commented Jun 4, 2018 at 10:48

2 Answers 2

2

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); 
Sign up to request clarification or add additional context in comments.

Comments

1

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();

1 Comment

thx for the answer, but im looking for the relationship method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.