## Laravel 的 Eloquent 中的多表继承:一种更简洁的方法?

Barbara Streisand
发布: 2024-10-27 01:59:30
原创
515 人浏览过

## Multi-Table Inheritance in Laravel's Eloquent: A Cleaner Approach?

Laravel Eloquent 中的多表继承

实现单表继承听起来像是扩展模型的一个方便的解决方案,但它有一些缺点,例如由于查询特定列时存在大量 NULL 值和复杂性,数据库大小增加。相反,多表继承提供了一种更简洁的方法。

架构设计

为每个模型类型的共享列和唯一列创建单独的表。例如:

  • 帖子(shared_column)
  • 问题(question_column,question_column2)
  • 文章 (article_column,article_column2)

Eloquent 模型

定义 Post 模型作为父类。

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

为每个可发布类型创建 问题 等子模型。

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

用法

  • 检索所有帖子: $posts = Post::all();
  • 检索所有问题:$questions = Question::all();
  • 从帖子中获取问题列:$question_column2 = $post-> ;postable->question_column2;
  • 检查帖子的类型: echo 'type: '.get_class($post->postable);

创建新帖子模型

涉及在共享表(帖子)和特定类型表(问题)中创建记录。

<code class="php">$question = new Question(); // Create a question record
$question->question_column = 'test';
$question->save();

$post = new Post(); // Create a post record
$post->shared_column = 'New Question Post';
$post->save();

// Link them together
$question->post()->save($post);</code>
登录后复制

这种方法确保了更高效的数据库结构,并为 Laravel 中的模型继承提供了可扩展的解决方案。

以上是## Laravel 的 Eloquent 中的多表继承:一种更简洁的方法?的详细内容。更多信息请关注PHP中文网其他相关文章!

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