使用 Laravel 将两个模型合并为一个具有预先加载关系的分页查询
2022-08-30 21:18:52
我有两个模型,我想将它们合并到一个时间轴中。我已经能够通过在mysql中创建一个视图来规范化和合并表来做到这一点。我为此视图创建了一个模型。如果我不想要相关模型,这很有效。我已经通过在模型上重写getMorphClass
方法来实现这一点。这允许我获得图片的相关评论,但不能获得帖子,因为当被称为模型时没有任何数据。NewsFeed
Comment
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 View
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