我有两个模型,我想将它们合并到一个时间轴中。我已经能够通过在mysql中创建一个视图来实现这一点,该视图对表进行规范化和联合。我为此视图创建了一个模型NewsFeed
。如果我不想要相关的Comment
模型,这会很好地工作。通过在模型上重写getMorphClass
方法,我已经接近了这一点。这让我可以获得图片的相关评论,但不能获得帖子,因为当调用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
您非常接近构建视图的想法。事实上,如果您创建一个实际的表而不是视图,那么解决方案就会变得非常简单。
通过一个指向Post类或Picture类的"FeedItem"多态对象,您可以使用hasMany关系将注释直接附加到FeedItem。
class FeedItem extends Model {
use CommentableTrait;
public function feedable()
{
return $this->morphTo();
}
}
class Post extends Model {
public function feeditem()
{
return $this->morphOne('FeedItem', 'feedable');
}
}
class Picture extends Model {
public function feeditem()
{
return $this->morphOne('FeedItem', 'feedable');
}
}
这个解决方案可能需要对表单进行一些重构,因为您需要为每个Post条目和Picture条目创建一个FeedItem条目。Picture::created和Post::created的事件侦听器应该完成此操作(http://laravel.com/docs/5.1/eloquent#events)。
一旦设置好,您可以使用:
FeedItem::with('comments')->orderBy('created_at','desc')->paginate(15);
尽管我对Laravel和Eloquent都不熟悉,但以下是我对此的看法。
假设您正在将该SQL视图的输出转换为$Entries
据我所知,Eloquent允许您自己设置值,因此这样的东西可能对您有用(我不确定这方面的语法或用法)。
$Collection = [];
foreach( $Entries as $Entry ) {
if( $Entry->type === 'post' ) {
$Collection[] = new Post($Entry->toArray())->with('comments');
}else{
$Collection[] = new Picture($Entry->toArray())->with('comments');
}
}
return $Collection;