我遇到了一个我无法通过的问题,下面是我的模特:
Cloth.php
public function selling(): BelongsTo
{
return $this->belongsTo(Selling::class);
}Selling.php
public function clothes(): HasMany
{
return $this->hasMany(Cloth::class);
},现在一切都好了,很基本.但随后出现了这样的模式:
Accessory.php
public function selling(): BelongsTo
{
return $this->belongsTo(Selling::class);
}现在问题是:我需要(我想)一个多态关系,但我不知道如何在这个特定的情况下做到这一点。我有2个启动模型到1个模型,但我发现的每一个例子都有一个开始模型到2个模型。我需要多态关系吗?我真的无法摆脱这一切。
谢谢!
发布于 2022-01-24 15:08:39
你基本上是在寻找一个到多个多态关系。以下是如何做到这一点:
比方说,你的桌子的结构就像低音;
Schema::create('sellings', function (Blueprint $table) {
$table->id();
$table->integer('relation_id');
$table->string('relation_type');
$table->timestamps();
});
Schema::create('accessories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('details');
$table->timestamps();
});
Schema::create('cloths', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('description');
$table->timestamps();
});Selling.php
public function relation(){
return $this->morphTo();
}Cloth.php
public function selling(){
return $this->morphOne(Selling::class, 'relation');
}Accessories.php
public function selling(){
return $this->morphOne(Selling::class, 'relation');
}然后,您可以使用bellow方法进行查询;
$selling = Selling::findOrFail(1)->relation;现在,当你dd($selling),你得到了你想要的东西,从一个对应的表;

请记住,relation_type字段需要精确地对应模型。例如,见下面的截图;

这里的情况是,当您创建一个名为test的多态函数时,数据库字段需要遵循对应于模型的test_type和对应于模型/数据库表的id的test_id。
https://stackoverflow.com/questions/70834508
复制相似问题