【问题标题】:laravel model morph to itself and other modelslaravel 模型变形为自身和其他模型
【发布时间】:2019-11-19 00:54:55
【问题描述】:

我误解了 laravel elequent 模型的概念 我有一个名为 Article 的模型,它有一个带有列的表格

        $table->bigIncrements('id');
        $table->string('title')->nullable();
        $table->string('slug')->index()->nullable();
        $table->string('feature_image')->nullable();
        $table->text('intro')->nullable();
        $table->text('content')->nullable();
        $table->string('seo_title')->nullable();
        $table->string('seo_meta')->nullable();
        $table->string('seo_keywords')->nullable();
        $table->smallInteger('state')->default(0)->index();
        $table->string('lang')->default('fa')->index();
        $table->softDeletes();
        $table->timestamps();

也是一个产品模型,名称为 products 和一些列 我想为每篇文章和产品模型提供相关文章和产品 我的意思是我想在创建新文章记录时为文章保存相关文章,对于产品也是如此 任何提示都会有所帮助。

如果我只想拥有一篇文章的相关文章呢?

【问题讨论】:

标签: php laravel


【解决方案1】:

我的解决方案如下(文章模型)。在迁移中,我添加了一列

$table->integer('master')->unsigned()->after('user_id')->default(0)->index()
                  ->comment('Articles can be linked to an other article');

模型和关系:

 /**
     * An article can belong to another article
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo Article
     */
    public function parent()
    {
        return $this->belongsTo(Article::class, 'master', 'id');
    }

    /**
     * An article can have many linked articles
     *
     * @return HasMany Article
     */
    public function children()
    {
        return $this->hasMany(Article::class, 'master', 'id');
    }

在控制器中,基本上:

$articles = Article::where('master', '0')->with('children')->get();

终于看到了:

@foreach($articles as $article)
     @include('articles.article_item_well', ['recursive' => true])
@endforeach

在“articles.article_item_well”的底部添加:

@if ($recursive && count($article->children) > 0)
    <div class="card-body">
        @foreach($article->children as $article)
            @include('articles.article_item_well')
        @endforeach
    </div>
@endif

刀片 sn-p 'articles.article_item_well' 打印出每篇文章的位置,无论嵌套多深。

这个系统只有一个问题(据我所知)无法解决。这就是分页。没有办法将孩子和孩子的孩子分页到每页总共 15 个。它将需要 15 篇“主”文章(值为 '0),并且不知道其中嵌套了多少文章。我试图解决这个问题,到处寻找,但无济于事。在我的情况下,这并不重要。

【讨论】:

  • 谢谢,但实际上它不是正确的解决方案,在您的回答中,我们将模型与自身一对一相关联并在递归循环中检索它们,实际上我正在寻找的是很多对于一个模型的许多数据透视表,我这样做了,但没有机会。我正在考虑在我的文章表中创建一个字段来保存与特定文章相关的文章 ID 数组
猜你喜欢
  • 2021-07-21
  • 1970-01-01
  • 2016-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-11
  • 2021-12-26
相关资源
最近更新 更多