我想在应用程序的首页上构建通知流。 现在,我有新闻,会议和演示的模型。 我想将这些元素组合成一个对象,可能称为事件,这样我就可以获取最新的5个事件并在首页上显示它们。 输出将是这样的:
News Article: Submissions open starting April 1 Presentatiion: How to do stuff, the PDF Meeting: April 15, Foo High School Gymnasium这些对象都实现了一个需要getTitle,getBody和getCreationDate的接口,因此每个对象都可以使用这些函数。
我不想简单地合并集合,因为它变得混乱。 有没有办法将这些对象组合成一个对象?
I want to build a notification stream on the front page of an application. Right now, I have models for News, Meetings, and Presentations. I want to combine these elements into a single object, perhaps called Events, so that I can then take the most recent 5 Events and display them on the front page. The output would be something like:
News Article: Submissions open starting April 1 Presentatiion: How to do stuff, the PDF Meeting: April 15, Foo High School GymnasiumThe objects all implement an interface which requires getTitle, getBody and getCreationDate, so these functions are available to each object.
I don't want to simply merge the collections, as that gets messy. Is there any way to combine these objects into a single object?
最满意答案
似乎是继承的经典案例。 您可以创建一个名为Event的模型。
class Event extends Model然后你提到的类将扩展事件。
class Article extends Event class Presentation extends Event class Meeting extends Event然后你可以在Event类上创建一个自定义方法。 我认为如果你想避免合并集合,那么在你的情况下编写简单的SQL比使用Eloquent更简单。
public function getUpcomingEvents() { // something like that, you get the idea return DB::select(' (SELECT title, body, CreationDate FROM articles LIMIT 5) UNION (SELECT title, body, CreationDate FROM meetings LIMIT 5) ORDER BY CreationDate DESC LIMIT 5')->get(); }这将使您的控制器保持干净和漂亮,模型结构将代表底层逻辑。
Seems like a classic case for inheritance. You can create a model called Event.
class Event extends ModelThen your mentioned classes would extend the Event.
class Article extends Event class Presentation extends Event class Meeting extends EventThen you could make a custom method on Event class. I think it would be simpler to write straightforward SQL than mess with Eloquent in your case, if you wish to avoid merging collections.
public function getUpcomingEvents() { // something like that, you get the idea return DB::select(' (SELECT title, body, CreationDate FROM articles LIMIT 5) UNION (SELECT title, body, CreationDate FROM meetings LIMIT 5) ORDER BY CreationDate DESC LIMIT 5')->get(); }This would keep your controllers clean and nice and models structure would represent the underlying logic.
更多推荐
发布评论