简体   繁体   中英

Laravel - sync with extra column

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?

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

I can confirm that it was a bug in Laravel 5 commit I used. I've upgraded for Laravel 5 final version and now query is generated as it should.

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