doumi0737 2015-01-31 12:07
浏览 35

Laravel - 与额外列同步

I have 3 tables

type

type_id

person

person_id

category

category_id
table_name
table_id
person_id

In category I have connections of different tables/models with Type model, So if I have want to get type_id connected with person with person_id = 23 the query should look like this:

SELECT * FROM category WHERE table_name='person' AND table_id = 23

In my Person model I defined relationship with Type this way:

public function groups()
{
    return $this->belongsToMany('Type', 'category',
        'table_id', 'type_id')->wherePivot( 'table_name', '=', 'person' );
}

When I want to get those types and I use:

$person->groups()->get()

The query looks like this:

select `type`.*, `category`.`table_id` as `pivot_table_id`, `category`.`type_id` as `pivot_type_id` from `type` inner join `category` on `type`.`type_id` = `category`.`type_id` where `category`.`table_id` = '23' and `category`.`table_name` = 'person';

so it seems to be correct.

But I would like to use sync() for synchronizing types with persons and here's the problem.

When I use:

$person->groups()->sync('1' => ['table_name' => 'person']);

I see the query that gets all records from category to use for sync looks like this:

select `type_id` from `category` where `table_id` = '23';

so it doesn't use

`category`.`table_name` = 'person'

condition so synchronization won't work as expected.

Is there any simple way to solve it or should I synchronize it manually?

  • 写回答

2条回答 默认 最新

  • douyuan9512 2015-01-31 12:33
    关注

    You should use Eloquents polymorphic relations (http://laravel.com/docs/4.2/eloquent#relationships)

    class Category extends Eloquent {
    
        public function categorizable()
        {
            return $this->morphTo();
        }
    
    }
    
    class Person extends Eloquent {
    
        public function categories()
        {
            return $this->morphMany('Category', 'categorizable');
        }
    
    }
    

    Now we can retrieve catgories from person:

    $person = Person::find(1);
    
    foreach ($person->categories as $category)
    {
        //
    }
    

    and access person or other owner from category:

    $category = Category::find(1);
    
    $categorizable_model = $category->categorizable; //e.g. Person
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?