lundi 31 juillet 2017

Error in converting relational collection to Json

I trying to get records from 2 tables,

One table is position and another one is items which have parent_id. this is some sample data:

Table: position

title    
----------
admin
user

Table: items

id   |  position  |  title  |  parent_id
-----+------------+---------+------------
1    | admin      | Test    | 0
2    | admin      | Test 2  | 0
3    | admin      | Test 3  | 2
4    | admin      | Test 4  | 3
5    | user       | Test 2  | 0

parent_id in this table refer to parent record in this table.

This is my models relations:

Model: Items

    public function child()
    {
        return $this->hasMany(self::class, 'parent_id', 'id');
    }

    public function children()
    {
        return $this->child()->with('children');
    }

Model: Position

public function pos()
    {
        return $this->hasMany('App\Models\Items', 'position', 'title');
    }

    public function pos_children()
    {
        return $this->pos()->with('children')->where('parent_id', '=', 0);
    }

Now I trying to get all positions with items so I wrote this code in my controller:

NavigationPosition::with('pos_children')->get();

Everything is OK until now and all records will fetch from database but I have problem when I use toJson() method :

NavigationPosition::with('pos_children')->get()->toJson();

I will get this error:

(1/1) BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::getHasActiveAttribute()

What should I do?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire