我有两个模型,我想将它们合并到一个时间轴中。我已经能够通过在mysql中创建一个视图来实现这一点,该视图可以对表进行规范化和联合。我为此视图创建了一个模型NewsFeed
。如果我不想要相关的Comment
模型,这很好用。通过覆盖模型上的getMorphClass
方法,我已经接近了这一点。这允许我获取图片的相关评论,但不能获取帖子,因为当调用getMorphClass
时,模型没有任何数据。
我对如何解决这个问题的任何方法都持开放态度,不仅仅是我提出的方法,但我不想从数据库中提取更多的数据。
NewsFeed
<?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
发布于 2015-11-01 14:35:49
您构建视图的想法非常接近您的想法。实际上,如果您创建一个实际的表而不是视图,那么解决方案就会变得非常简单。
使用指向您的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');
}
}
这个解决方案可能需要对表单进行一些重构,因为您需要为每个帖子条目和图片条目创建一个FeedItem条目。Picture::created和Post::created的事件侦听器应该能完成任务(http://laravel.com/docs/5.1/eloquent#events)。
设置完成后,您可以使用:
FeedItem::with('comments')->orderBy('created_at','desc')->paginate(15);
发布于 2015-11-03 01:53:14
虽然我对Laravel并不熟悉,也不是很有说服力,但这里是我对此的看法。
假设您正在将该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;
https://stackoverflow.com/questions/33354721
复制相似问题