2015-10-04 55 views
0

我正在使用Laravel 5.1及其与MySQL的雄辩模型。我可以从静态数组中填充Eloquent模型的集合吗?

但我想填充一个模型集合获取一个静态数组,然后查询它是正常的。 所以我们可以说我有我的照片模式,我想查询它像往常一样:

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

但照片的模型不应该取一个数据表,但像这样的数组:

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

我的问题是在查询之前将该数组链接到该模型。 任何想法?

+0

你能提供一个例子,字段的数组是什么型号? –

+0

我认为这个文档可以解决你的问题,请阅读这个文档http://laravel.com/docs/5.1/eloquent-collections,一旦你用雄辩的数据获取数据,你可以反复过滤记录查询回数据库。 – umefarooq

+0

@KA_lin我不能,因为我甚至不知道它是否可能。 –

回答

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); 
    } 
    .... 
} 
0

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

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

因此,你可以查询以往的方式,你想拥有它返回放在里面列出的功能