【发布时间】:2022-01-14 14:31:48
【问题描述】:
我有以下型号。
-
Player- (
hasMany(Monster::class))
- (
-
MonsterhasOne(MonsterSpecies::class,'id','species_id')-
hasOne(MonsterColor::class,'id','color_id'))
MonsterSpecies-
MonsterColor- (两者几乎都是空的,只是
public $timestamps = false;)
- (两者几乎都是空的,只是
然后,播种后,在php artisan tinker 中选择一名玩家:
$player = Player::all()->first();
它有效。然后我检查怪物。
Illuminate\Database\Eloquent\Collection {#3561
all: [
App\Models\Monster {#3569
id: 1,
created_at: "2021-12-09 16:39:29",
updated_at: "2021-12-09 16:39:29",
name: "Alberto Mills",
level: 17,
currHealth: 68,
maxHealth: 76,
strength: 42,
defense: 29,
movement: 13,
species: 28,
color: 34,
player_id: 1,
},
App\Models\Monster {#4505
id: 2,
created_at: "2021-12-09 16:39:29",
updated_at: "2021-12-09 16:39:29",
name: "Darlene Price",
level: 9,
currHealth: 16,
maxHealth: 32,
strength: 44,
defense: 19,
movement: 61,
species: 28,
color: 34,
player_id: 1,
},
],
}
然后$player->monster->get(0)->color;
App\Models\MonsterColor {#4508
id: 34,
name: "Red_Blue",
}
现在我相信我可以添加 getSpeciesAttribute() 和 getSpeciesAttribute() 来直接返回名称,或者执行以下操作:
public function getSpeciesAttribute($value)
{
$colors = explode("_",$value->name); // I don't know if this is how I get the name
$out = "Your monster's color is ";
if (count($colors) > 1) {
$out .= "a mesh of " . implode(", ",array_slice($colors, 0, -1)) . " and ";
}
$out .= array_pop($colors);
return $out;
}
但我不知道如何访问MonsterColor 的name 属性。
编辑:
这是 Monster、MonsterColor 和 MonsterSpecies 模型。
class Monster extends Model
{
use HasFactory;
protected $fillable = [
'name',
'level',
'currHealth',
'maxHealth',
'strength',
'defense',
'movement',
'species',
'color'
];
public function player()
{
return $this->belongsTo(Player::class);
}
public function species()
{
return $this->hasOne(MonsterSpecies::class,'id','species_id');
}
public function color()
{
return $this->hasOne(MonsterColor::class,'id','color_id');
}
public function getSpeciesAttribute()
{
return $this->species->name;
}
public function getColorAttribute()
{
return $this->color->name;
}
}
class MonsterColor extends Model
{
use HasFactory;
public $timestamps = false;
}
class MonsterSpecies extends Model
{
use HasFactory;
public $timestamps = false;
}
【问题讨论】:
-
getSpeciesAttribute是什么型号的? -
@Andy on Monster,用 Monster 类更新了 OP。
-
看起来您在编辑中的内容应该可以工作..您是否遇到某种错误或意外行为?如果我不得不猜测,我认为您会遇到具有相同名称的关系和属性的问题。
-
可能对他有用,他想要我认为加入 laravel 的所有属性我猜
Monster::with("player")->with("species")->with("color")->get();Player::with("monster",function($e){ $e->with("species")->with("color")->get(); });