Laravel 关系和where子句?

Laravel 关系和where子句?,laravel,laravel-4,eloquent,Laravel,Laravel 4,Eloquent,我有以下表格: **galleries** id location open_to_public **pictures** id title published **gallery_picture** gallery_id picture_id 这是我的画廊模型: class Galleries extends Eloquent { protected $table = 'galleries'; public function pictures(){ return $thi

我有以下表格:

**galleries**

id
location
open_to_public

**pictures**
id
title
published

**gallery_picture**
gallery_id
picture_id
这是我的画廊模型:

class Galleries extends Eloquent {

protected $table = 'galleries';

public function pictures(){

    return $this->belongsToMany('pictures', 'gallery_picture', 'gallery_id', 'picture_id');

}
我正在尝试选择画廊id、位置,并获取相关图片id、标题

首先,我尝试过这个,但它似乎返回了大量的数据,我不确定我是否做得正确

$this->mGalleries = new Galleries;
return $this->mGalleries->pictures();
我还想为查询添加一些约束,我知道我可以这样做:

public function scopePublic()
{
        return $query->where('open_to_public','=',1);
}
然后: 返回$this->mGalleries->pictures->public

但我还没有正确地实施这一点。有人能给我指一下正确的方向吗

我想获取gallery.id、gallery.location以及gallery.open_to_public=1的所有画廊图片,并仅获取已发布的图片=1


此外,我还想获得与上述条件相关的所有库,而不仅仅是一个库。

如果没有您收到的具体错误,很难说她到底发生了什么,但从您的代码示例中我突然想到的一件事是,您不接受$query作为scope方法的参数。请尝试以下代码:

public function scopePublic($query)
{
        return $query->where('open_to_public','=',1);
}
除此之外,您似乎在错误的对象上调用作用域函数。根据您的描述,您需要如下设置:

画廊模型 scopePublic$查询 图像模型 scopePublished$query 此外,您只能获得单个图库的图片,而不能一次性获得所有图库的图片。因此,您不能像预期的那样使用Gallery::all->pictures,而是必须创建自己的收藏库

最终的代码将如下所示:

// empty collection to store all our pictures
$pictures = new \Illuminate\Database\Eloquent\Collection;

// get all galleries open to the public
$galleries = Gallery::public()->get();

// for each gallery, get its pictures and add it to the collection
$galleries->each(function ($gallery) use ($pictures) {
    $pictures->merge($gallery->pictures()->published()->get());
});
但是,有几种不同的方法可以做到这一点。您可能会发现,预加载关系也有助于数据库查询查找Eloquent's,并查看是否有某种方式可以在其中传递范围调用。或者,如果Eloquent的语法有点过于冗长,您可以尝试使用DB类并手动连接


另外,如果代码有问题,很抱歉,它未经测试,但至少应该为您提供一个解决此问题的基础。

谢谢,我仍然有很多基础知识:objectIlluminate\Database\elounce\Galleries196 1{[items:protected]=>array0{},据我所知,它是空的,但是我的数据库里有数据,叫做via:$this->mGalleries->pictures->get;是的,但正如我说的,你不能直接在类上调用一个belongToMany关系-你需要一个实例。当你调用$this->mGalleries->pictures时,你想说的是获取所有与{我不在乎哪个库}相关的图片,但你需要说获取所有与{给定库}相关的图片-所以你需要像$this->mGalleries->find1->pictures这样的东西-它可以获取与id为1的图库关联的所有图片。