我可以从静态数组填充Eloquent模型的集合吗?


Can I populate a collection of Eloquent models from a static array?

我使用的是Laravel 5.1和它的Eloquent模型。

但是我想填充一个模型的集合,获取一个静态数组,然后像正常一样查询它。假设我有我的Photo模型我会像往常一样查询它:

App'Photo::where('published', 1)->get();

但是Photo模型不应该获取DB表,而是像这样获取数组:

$photos = [ 
    [ "id" => 1, "published" => 1 ],
    [ "id" => 2, "published" => 1 ],
    [ "id" => 2, "published" => 0 ],
]

我的问题是在查询它之前将这个数组链接到那个模型。什么好主意吗?

不知道你为什么要这样做,但如果我是你,我会把每个查询方法放在一个服务类中:

namespace App'Services;
class PhotoService implements PhotoServiceInterface
{
    public function getAllPhotos() {
        return App'Photo::$photos;
    }
    //your static array defined in the class as an associative array, you should use **try** **catch** for this or define a default if the key does not exist
    public static function getPhotoById($id) {
        return App'Photo::$photos[$id];
    }
    //other functions
    public function getAllAlbums() {
        return App'Albums::all();
    }
}

这样,如果你想把它们放在一个表中,或者在你的应用程序中发生其他变化,你只需要改变这个类。

问题:如果您有一个与此模型有关系的模型,则必须使用服务来获取它(getPhotoById($user->getPhotoId())),而不是使用前$user->getPhoto()。或者你可以:

class User
{
    ....
    public function getPhoto() {
        return App'Services'PhotoService::getPhotoById($this->photo_id);
    }
    ....
}

使用列表功能将返回您在查询中指定的列数组。

 App'Photo::where('published', 1)->lists('id','published');

因此,您可以查询模型的任何方式,你想让它返回一个数组的字段放置在列表的功能