mercredi 31 octobre 2018

Laravel relationtable with many to many

Im stuck on how to connect my users with other tables in a clean way. I've tried to work with laravel polymorphic table handling without success. This is what my tables look like, ( ignore the plural use of equipment and armor, will change later).

A user will have many equipments which points to one weapon or armor.

:: users ::
id
name

:: equipments ::
id
user_id
equipmentable_id
equipmentable_type

:: weapons ::
id
name

:: armors ::
id
name

What i would like to do is to get weapons and armors of users

$user->weapons ( Should return all weapons )
$user->armors ( Should return all armors )

This is my current attempt using larvel polymorphic tables

UserModel:

class User extends Authenticatable
{
    public function equipments()
    {
      return $this->hasMany(Equipment::class);
    }
}

EquipmentModel:

class Equipment extends Model
{
    public function equipments()
   {
     return $this->morphTo();
   }

   public function weapons()
   {
     return $this->equipments()->where('equipmentable_id', 'App\Weapon');
   }

   public function armors()
   {
     return $this->equipments()->where('equipmentable_type', 'App\Armor');
   }

}



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

Aucun commentaire:

Enregistrer un commentaire