Mahmoud Abd AL Kareem
Mahmoud Abd AL Kareem

Reputation: 645

change relation records Laravel5.2

I have the following problem, I have two models Level and Class: Level has the relation classes() ,then after getting level classes :

$level->classes

the data returned is like this: { "id": 1, "name": "class 1" }, { "id": 2, "name": "class 2" } now I want to discard class 2 , I tried this but it doesn't work :

        $ids=[2];
        $classes=$level->classes;

        $classes=$classes->whereIn('id',$ids);

        $level->classes=$classes;

Any suggestions ?

Upvotes: 0

Views: 43

Answers (2)

Damir Miladinov
Damir Miladinov

Reputation: 1374

Use this: $level->classes()->whereIn('id', $ids)->get().

This will return an instance of Relation class, which has all the methods as a normal query builder.

Upvotes: 1

Chris Kloberdanz
Chris Kloberdanz

Reputation: 4536

You might be able to use eager loading to accomplish what you want. If you just want one Level you'd have to add constraint for that as well after the ')' and before the '->get();'

https://laravel.com/docs/5.2/eloquent-relationships#eager-loading

$ids = [2];

$levels = Level::with(
    [
        'classes' => function ($query) use ($ids) {
            $query->whereIn('id', $ids);
        }
    ]
)->get();

Upvotes: 1

Related Questions