php - 使用多个模型和集合 - 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 之前,它可以位于中间吗?
解决方案
推荐阅读
- python - 如何使用 python 将证书安装到受信任的根证书?
- python - 在 Python 上,我的解决方案没有响应正确的代码
- javascript - 在会话存储中保存完整的 JSON
- java - 找不到类 javax.xml.bind.JAXBElement 的主构造函数或默认构造函数
- google-cloud-platform - 增加谷歌云虚拟机的配额
- snowflake-cloud-data-platform - 雪花接收器连接器 - 状态失败 java.lang.NoClassDefFoundError org/bouncycastle/jcajce/provider/BouncyCastleFipsProvider
- powerbi - 表中的 Power BI DISTINCTCOUNT 值随切片器更改
- spring-boot - 带有集成测试的 Jacoco 多模块 - 未涵盖 REST 控制器
- laravel - Laravel 字符串在输入时降低
- java - 如何使用 Method 类型的值进行枚举