首页 > 解决方案 > 使用多个模型和集合 - Laravel

问题描述

在我的 Laravel 应用程序中,我有一个 Articles 表、一个 Facebook 帖子表和一个 Tweets 表。这些在查询时为我提供了三个集合。

例如

$articles = App\Article::get();
$tweet_posts= App\Facebook::get();
$facebook_posts= App\Twitter::get();

我要做的是在一个页面上显示所有文章、推文和 Facebook 帖子,就像一个大新闻提要,按日期顺序排序。

数据位于单独的表中,并具有单独的模型。

文章迁移如下所示:

Schema::create('articles', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->string('excerpt')->nullable();
    $table->mediumText('content')->nullable();
    $table->string('featuredImage')->nullable();
    $table->mediumText('featuredVideo')->nullable();
    $table->string('author')->nullable();
    $table->string('readingTime', 15)->nullable();
    $table->string('category')->nullable();
    $table->string('published')->default('pending');
    $table->boolean('featuredArticle')->default(0);
    $table->timestamps();
});

Facebook 和 Twitter 迁移看起来像这样:

Schema::create('facebook_posts', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->mediumText('content')->nullable();
    $table->string('featuredImage')->nullable();
    $table->timestamps();
});

Schema::create('twitter_posts', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->mediumText('content')->nullable();
    $table->string('featuredImage')->nullable();
    $table->timestamps();
});

在这种情况下,Facebook 和 Twitter 表在字段方面的数据属性明显少于文章。

基本上我想做的是让一个人foreach loop浏览所有三个表中的所有内容,然后根据模型类型分配样式。

那么,是否可以将 3 个集合合并为一个大集合,然后为某些模型没有的其他字段设置空值?

在视图中(如果所有内容都合并了),我会设想这样的事情:

@foreach($feeds as $feed)
    @if($feed->type == 'tweet')
    // Twitter styled block
        {{ $feed->title }}
    @endif
@endforeach

其中 feed 是合并的集合,->type是获取模型类型的全局查询范围。例如应用\文章。

或者,如果我要返回包含三个集合的视图,是否有办法按日期顺序对项目进行排序,但不限于集合类型?

例如,如果推文 1 在 Facebook 帖子 3 之前,它可以位于中间吗?

标签: phplaravel

解决方案


推荐阅读