我使用Laravel 5.1及其带有mysql的Eloquent模型。
但是我想填充一组模型来获取静态数组,然后正常查询它。 所以,让我说我有我的照片模型,我会照常查询:
App\Photo::where('published', 1)->get();
但Photo模型不应该获取数据库表,而应该获取这样的数组:
$photos = [
[ "id" => 1, "published" => 1 ],
[ "id" => 2, "published" => 1 ],
[ "id" => 2, "published" => 0 ],
]
我的问题是在查询之前将此数组链接到该模型。 有什么想法吗?
答案 0 :(得分: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())
)而不是ex $user->getPhoto()
。
或者你可以:
class User
{
....
public function getPhoto() {
return App\Services\PhotoService::getPhotoById($this->photo_id);
}
....
}
答案 1 :(得分:0)
使用列表功能将返回您在查询中指定的列数组。
App\Photo::where('published', 1)->lists('id','published');
因此,你可以查询模型你希望它返回列表功能中放置的字段数组