search

Home  >  Q&A  >  body text

Association object - laravel\lumen How should conditional association be handled?

I currently have 3 tables, tags, product, album.

The tags associated with

product and album are all in tags. Distinguish by biz_type, 1 means product, 2 means album.

The table relationship is as follows

table_tags
    id: int
    biz_type: int 
    biz_id: int

table_product
    id: int

table_album
    id: int

I now hope to obtain the information of product and album by querying the paging list of tags.
Currently I have checked the polymorphic association of laravel, and it seems that this approach is not supported. Is there any way to relate through conditions?

给我你的怀抱给我你的怀抱2799 days ago593

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-05-16 16:53:56

    Laravel’s polymorphic many-to-many association talks about this. This usage scenario is somewhat similar to yours. You can take a look
    http://www.kancloud.cn/baidu/...

    Polymorphic Many To Many Relation Table Structure Polymorphic many to many relational database table structure

    In addition to general polymorphic associations, many-to-many polymorphic associations can also be used. For example, the Post and Video models of Blog can share the polymorphic Tag association model. First, let’s take a look at the database table structure:

    posts

    id - integer
    name - string

    videos

    id - integer
    name - string

    tags

    id - integer
    name - string

    taggables

    tag_id - integer
    taggable_id - integer
    taggable_type - string

    Now, we are ready to set up the model association. Both Post and Video models can establish morphToMany associations via the tags method:

    class Post extends Model {

    public function tags()
    {
        return $this->morphToMany('App\Tag', 'taggable');
    }

    }
    Create a method for each association in the Tag model:

    class Tag extends Model {

    public function posts()
    {
        return $this->morphedByMany('App\Post', 'taggable');
    }
    public function videos()
    {
        return $this->morphedByMany('App\Video', 'taggable');
    }

    }

    reply
    0
  • 某草草

    某草草2017-05-16 16:53:56

    join? But it is not recommended.

    reply
    0
  • 怪我咯

    怪我咯2017-05-16 16:53:56

    You can also implement a correlation query yourself. Currently, the framework does not provide conditional queries for polymorphic correlations because they are too complex.

    reply
    0
  • Cancelreply