【发布时间】:2016-01-26 01:58:05
【问题描述】:
我想将两个模型合并到一个时间轴中。我已经能够通过在 mysql 中创建一个视图来规范化和合并表来做到这一点。我为此视图创建了一个模型,NewsFeed。如果我不想要相关的Comment 模型,这很有效。通过覆盖模型上的getMorphClass 方法,我已经接近了这一点。这使我可以获取图片的相关 cmets,但不能获取帖子,因为当调用 getMorphClass 时,模型没有任何数据。
我对如何解决这个问题的任何方法持开放态度,而不仅仅是我提议的方式,但我不想从数据库中提取更多数据。
新闻源
<?php
namespace App\Users;
use App\Pictures\Picture;
use App\Social\Comments\CommentableTrait;
use App\Posts\Post;
use App\Users\User;
use Illuminate\Database\Eloquent\Model;
class UserFeed extends Model
{
use CommentableTrait;
public function user()
{
return $this->belongsTo(User::class);
}
public function getMorphClass(){
if ($this->type == 'post'){
return Post::class;
}
return Picture::class;
}
}
MySQL 视图
CREATE VIEW
`user_feeds`
AS SELECT
`posts`.`id` AS `id`,
`posts`.`user_id` AS `user_id`,
'post' AS `type`,
NULL AS `name`,
NULL AS `thumbnail`,
`posts`.`body` AS `body`,
`posts`.`updated_at` AS `updated_at`,
`posts`.`created_at` AS `created_at`
FROM
`posts`
UNION SELECT
`pictures`.`id` AS `id`,
`pictures`.`user_id` AS `user_id`,
'picture' AS `type`,
`pictures`.`name` AS `name`,
`pictures`.`thumbnail` AS `thumbnail`,
`pictures`.`description` AS `body`,
`pictures`.`updated_at` AS `updated_at`,
`pictures`.`created_at` AS `created_at`
FROM
`pictures`;
图片表
id
user_id
title
img
img_width
img_height
img_other
description
created_at
updated_at
帖子
id
user_id
title
body
created_at
updated_at
【问题讨论】:
-
你不能只使用急切加载吗? $var = Picture::with('posts','cmets')...
-
最接近的是获取 User::with(['posts','pictures'])->get();这不会让你分页内容。我想过做一些类似
$user->posts()->paginate(15);和$user->pictures()->paginate(15);然后合并集合的事情,但是一旦你想要更多的记录集就会出现问题。 -
为什么不分页
User::with(['posts','pictures'])->paginate(15);甚至User::with(['posts','posts.comments','pictures'])->paginate(15);并在帖子模型上拉一个 cmets 方法呢? -
因为这可以让您获得 15 个用户,而不是一个用户根据 created_at 日期拥有 15 张图片和帖子的混合集合。
-
您可以
collect所有结果并从那里分页。collect([$user->posts, $user->pictures])->sortBy('created_date')->forPage($page, 15);
标签: php mysql laravel laravel-5.1