Laravel 与多对多相关
Laravel relationtable with many to many
我一直在思考如何以干净的方式将我的用户与其他 table 联系起来。我尝试使用 laravel 多态 table 处理但没有成功。这是我的table的样子,(忽略装备和防具的复数使用,稍后会更改)。
一个用户会有很多装备,这些装备都指向一件武器或者防具。
:: users ::
id
name
:: equipment ::
id
user_id
equipment_id
equipment_type
:: weapons ::
id
name
:: armors ::
id
name
我想做的是获得用户的武器和防具
$user->weapons ( Should return all weapons )
$user->armors ( Should return all armors )
在我的数据库中,我在设备中有 2 条记录 table:
id: 1
user_id: 21 (current user)
equipment_id = 1 (id of a weapon in weapons table)
equipment_type = weapon (string)
id: 2
user_id: 21 (current user)
equipment_id = 2 (id of a weapon in weapons table)
equipment_type = weapon (string)
这是我目前使用 larvel 多态 tables
的尝试
用户模型:
class User extends Authenticatable
{
public function weapons()
{
return $this->morphedByMany('App\Weapon', 'equipment');
}
}
武器型号:
class Weapon extends Model
{
public function users()
{
return $this->morphToMany('App\User', 'equipment');
}
}
equipment_type
列必须包含整个 class 名称,例如App\Weapon
.
或者,您可以在 AppServiceProvider::boot()
中定义自定义 $morphMap
:
Relation::morphMap([
'armor' => 'App\Armor',
'weapon' => 'App\Weapon',
]);
我一直在思考如何以干净的方式将我的用户与其他 table 联系起来。我尝试使用 laravel 多态 table 处理但没有成功。这是我的table的样子,(忽略装备和防具的复数使用,稍后会更改)。
一个用户会有很多装备,这些装备都指向一件武器或者防具。
:: users ::
id
name
:: equipment ::
id
user_id
equipment_id
equipment_type
:: weapons ::
id
name
:: armors ::
id
name
我想做的是获得用户的武器和防具
$user->weapons ( Should return all weapons )
$user->armors ( Should return all armors )
在我的数据库中,我在设备中有 2 条记录 table:
id: 1
user_id: 21 (current user)
equipment_id = 1 (id of a weapon in weapons table)
equipment_type = weapon (string)
id: 2
user_id: 21 (current user)
equipment_id = 2 (id of a weapon in weapons table)
equipment_type = weapon (string)
这是我目前使用 larvel 多态 tables
的尝试用户模型:
class User extends Authenticatable
{
public function weapons()
{
return $this->morphedByMany('App\Weapon', 'equipment');
}
}
武器型号:
class Weapon extends Model
{
public function users()
{
return $this->morphToMany('App\User', 'equipment');
}
}
equipment_type
列必须包含整个 class 名称,例如App\Weapon
.
或者,您可以在 AppServiceProvider::boot()
中定义自定义 $morphMap
:
Relation::morphMap([
'armor' => 'App\Armor',
'weapon' => 'App\Weapon',
]);