简体   繁体   中英

How I can get data from table laravel model

I got two tables (Models), tags with id and name and post_tag with post_id and tag_id.

How I can get from table tags name but with table post_tag post_id.

Look, you haven't given any code sample. But from your question, I guess that you've two model named, Tag & Post

So, your post_tag became the pivot table right. And it is a many-to-many relation.

In your Tag model build relation like,

public function postTag()
    {
        return $this->belongsToMany(Post::class, 'post_tag', 'tag_id', 'post_id');
    }

In same way, in your Post model add a relation like

public function tags()
    {
        return $this->belongsToMany(Tag::class, 'post_tag', 'post_id', 'tag_id');
    }

Now, your pivot relation is ready. At the time off attaching tags with Post , use $post->tags()->attach(Tag::find($tag)); // $post = new Post(); $tag is tag_id $post->tags()->attach(Tag::find($tag)); // $post = new Post(); $tag is tag_id

To retrieve all post with associated tags, call

Post::with('tags')->get();

Similarly, to get tags associated with post

Tag::with('postTag')->get();

Head to laravel official website for many-to-many relations documentationlaravel One To Many Eloquent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM