以下是一些专注于问题和答案格式的标题选项,使用问题格式: **选项 1(直接且清晰):** * **单表继承与多表继承:哪个我

Patricia Arquette
发布: 2024-10-24 22:01:02
原创
464 人浏览过

Here are a few title options that focus on the question and answer format, using a question format:

**Option 1 (Direct and Clear):**

* **Single Table Inheritance vs. Multi Table Inheritance: Which is Right for Your Laravel Model?**

**Option 2 (More Spe

Laravel Eloquent 单表继承

问题

您想要实现单表继承来创建多个模型类型,这些模型类型共享公共属性但又具有唯一属性.

解决方案:单表继承

考虑使用单表继承。在这种方法中,您有:

  • 绑定到单个表的基本 Post 模型。
  • 扩展 Post 的派生文章和问题模型。
  • 中的类型列Post 表来区分模型类型。

解决方案:多表继承

单表继承可能会导致空值。请考虑多表继承:

  • 每个模型类型(帖子、问题、文章)都有单独的表。
  • posts 表中的外键列(postable_id、postable_type)引用另一个表表。
  • Eloquent 模型中用于连接表的多态关系。

Eloquent 模型设置

Post

<code class="php">class Post extends Eloquent {
    public function postable() {
        return $this->morphTo();
    }
}</code>
登录后复制

问题 / 文章

<code class="php">class Question extends Post {
    public function post() {
        return $this->morphOne('Post', 'postable');
    }
}</code>
登录后复制

用法:

<code class="php">$posts = Post::all();
$questions = Question::all();

$post = Post::find(1);
$question_column2 = $post->postable->question_column2;
$shared_column = $question->post->shared_column;</code>
登录后复制

以上是以下是一些专注于问题和答案格式的标题选项,使用问题格式: **选项 1(直接且清晰):** * **单表继承与多表继承:哪个我的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!