mercredi 22 février 2017

How to use Polymorphic Relations in Laravel with all rows?

I'am new on Laravel, i use laravel 5.4 version. I have next scenario: i have one table for users where i put only username and pass, and two other tables employees and partners, where i keep all data for users like name, address, email, phone....

Tables structure:

users - id|username|password|userable_id|userable_type
employees - id|name|phone|email|salary|position|departamnet
partners - id|name|companyname

In User model:
class User extends Authenticatable
{
        public function userable(){
        return $this->morphTo();
    }
}

Class Model:
    class Employee extends Model
    {
        protected $fillable = [];
        public function users()
        {
            return $this->morphOne('App\User', 'userable');
        }
    }
Partner Model:
class Partner extends Model
{
    protected $fillable = [];
    public function users()
    {
        return $this->morphOne('App\User', 'userable');
    }
}

Now if i execute this (App\User::first()->userable )in tinker will return data from Employee/Partner only for the first user. for all() or get() methods will return this:

App\User::all()->userable Exception with message 'Property [userable] does not exist on this collection instance.' App\User::get()->userable Exception with message 'Property [userable] does not exist on this collection instance.'

It is any change to make this to work for all users list? PS: in users table on userable_type i have, a Model, and on userable_id i have row id that corresponds with model, for example Employee and 1. Thanks in advance.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lFBbMr
via IFTTT

Aucun commentaire:

Enregistrer un commentaire