[英]Laravel polymorphic relation in Nova
我当前的博客之类的应用程序具有一个Page
,该Page
可能具有许多不同结构的Paragraphs
(文本,图像,文件下载,注册表单等)。 尝试将其转换为具有关系的雄辩模型时,我认为这是一种简便的方法:
表格pages
:
表格paragraphs
:
表paragraph_texts
:
表paragraph_images
:
表格paragraph_downloads
:
和模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Page extends Model
{
public function paragraphs() {
return $this->hasMany(Paragraph::class);
}
}
?>
段落模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Paragraph extends Model
{
public $table = 'paragraphs';
public $timestamps = [];
public function page() {
return $this->belongsTo(Page::class);
}
public function paragraphable() {
return $this->morphTo();
}
}
文本类型模型作为示例:
<?php
namespace App\Models\ParagraphTypes;
use Illuminate\Database\Eloquent\Model;
class Text extends Model
{
protected $table = 'paragraph_texts';
public function paragraph() {
return $this->morphOne(Paragraph::class, 'paragraphable');
}
}
现在,我想以nova模式查看页面,并通过可选类型创建一个新段落。 我根据雄辩的关系(页面的HasMany字段,段落的MorphTo和文本类型的TextArea)创建了Resource类(用于页面,用于段落和每种段落类型)。 当我看到页面的详细信息并想要添加新段落时,可以看到添加段落的表单,并且可以在下拉列表中选择段落类型,但只能看到已经存在的条目,而不是新条目。 我永远都不想添加这样的现有段落类型。
所以问题:
关于第一个问题:您应该使用文档中的关系:
class Page extends Model
{
public function texts() {
return $this->morphedByMany(Text::class, 'paragraphable', 'paragraphs');
}
}
class Text extends Model
{
public function pages() {
return $this->morphToMany(Page::class, 'paragraphable', 'paragraphs');
}
}
您可以通过访问器获得多种段落类型:
class Page extends Model
{
public function getParagraphsAttribute() {
return $this->texts->toBase()->merge($this->files)->merge([...]);
}
}
$paragraphs = $page->paragraphs;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.