Laravel与类型的关系

时间:2018-10-31 00:45:27

标签: php laravel laravel-5

我一直试图找到最适合我的问题的解决方案,而没有得到我想要的。

我现在有4张桌子,结构看起来像这样。

:: Users ::
id
name
email
------

:: user_equipment ::
id
user_id
equipment_id
equipment_type

:: weapons ::
id
name
price

:: armor ::
id
name
price

我的目标是能够像这样使用我的关系:

$user->equipment
$user->equipment->weapons
$user->equipment->armor

这是我现在拥有的:

用户模型:

class User extends Model
{    
  public function equipment()
  {
    return $this->hasOne(UserEquipment::class);
  }
}

用户设备模型:

class UserEquipment extends Model
{
   public function weapons()
   {
     return $this->hasMany(Weapon::class);
   }
}

3 个答案:

答案 0 :(得分:1)

首先,您的User模型和UserEquipment模型具有相同的类名。

尝试一下,将您的user模型更改为

public function weapons()
{
    return $this->hasMany('App\Weapon', 'equipment_id')->where('equipment_type','weapon'); //second paramater tells what column to relate the id
} 

public function armors()
{
    return $this->hasMany('App\Armors', 'equipment_id')->where('equipment_type','armor'); 
}

然后是您的查询方式:

User::with('weapons', 'armors')->get();

答案 1 :(得分:0)

在我看来,这就像Many To Many Polymorphic Relationship

在您的情况下,您需要通过以下方式定义您的关系:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get all of the weapons owned by the user.
     */
    public function weapons()
    {
        return $this->morphedByMany('App\Weapon', 'equipment', 'user_equipment');
    }

    /**
     * Get all of the armors owned by the user.
     */
    public function armors()
    {
        return $this->morphedByMany('App\Armor', 'equipment', 'user_equipment');
    }
}

进行查询:

$user = App\User::find(1);

foreach ($user->weapons as $weapon) {
    //
}

foreach ($user->armors as $armor) {
    //
}

答案 2 :(得分:0)

尝试像这样更改表格:

:: Users ::
id
name
email
------

:: user_equipment ::
id
user_id
equipment_type

:: weapons ::
id
name
price
user_equipment_id

:: armor ::
id
name
price
user_equipment_id

然后,您可以像使用它们一样使用这些功能: 用户模型:

class User extends Model
{    
  public function equipment()
  {
    return $this->hasOne(UserEquipment::class);
  }
}

用户设备模型:

class UserEquipment extends Model
{
   public function weapons()
   {
     return $this->hasMany(Weapon::class);
   }
   public function armor()
   {
     return $this->hasMany(Armor::class);
   }
}

laravel中的注意事项Laravel在模型Weapons中假定存在外键调用user_equipment_idhttps://laravel.com/docs/5.7/eloquent-relationships#one-to-many