[英]Querying Models in Laravel
I would like to be able to write an eloquent query that I could pass in to this model function to return only categories that have stories published on $publishDate. 我希望能够编写一个雄辩的查询,将该查询传递给此模型函数,以仅返回在$ publishDate上发布了故事的类别。
EG - This is what I desire but I am getting the following error 'Call to undefined method Illuminate\\Database\\Query\\Builder::stories()' EG-这是我想要的,但出现以下错误“调用未定义的方法Illuminate \\ Database \\ Query \\ Builder :: stories()”
In my controller: 在我的控制器中:
Category::orderBy('id', 'ASC')->stories($publishDate)->get();
And in my Model: 在我的模型中:
public function stories($publishDate)
{
return $this->hasMany('Workbench\Dailies\Story', 'category_id')
->orderBy('story_title', 'ASC')
->where('publish_date', $publishDate);
}
I am sure this is something very simple but I can not quite figure it out. 我相信这很简单,但是我不太清楚。 Thanks in advance.
提前致谢。
relation: 关系:
public function stories()
{
return $this->hasMany('Workbench\Dailies\Story', 'category_id');
}
then 然后
// $publishedAt is some date you want
Category::whereHas('stories', function($query) use ($publishedAt) {
$query->where('published_at', '=', $publishedAt)->orderBy('story_title','asc');
})->orderBy('id','asc')->get();
I haven't found a way to do this in any similar way. 我还没有找到以任何类似方式执行此操作的方法。 The way I have found is similar to (in your context):
我发现的方式类似于(在您的上下文中):
Category::join('stories', 'categories.id', '=', 'stories.category_id')->where('stories.publish_date', '=', $publishDate)->orderBy('id', 'ASC')->get();
Although, I prefer using DB::select
with DB::raw
to select the fitered IDs only then with the ORM I do Category::whereIn('id', <returned IDs>)->get()
(in your context). 虽然,我更喜欢使用
DB::select
和DB::raw
来选择合适的ID,然后才使用ORM选择Category::whereIn('id', <returned IDs>)->get()
(在您的上下文中) 。
$sql = 'SELECT c.ID FROM categories c LEFT/INNER JOIN stories s ON (c.id = s.category_id) WHERE s.publish_date = ?';
$ids = DB::select(DB::raw($sql), array($publishDate));
// you can now iterate with array_walk, foreach, for, etc. the args to extract IDs from object rows
for($i = 0; $i < count($ids); $i++)
$ids[$i] = (int) $ids[$i]->id;
$cats = Category::whereIn('id', $ids)->orderBy('id', 'ASC')->get();
The bad is that part is not so well documented. 不好的是,该部分没有得到很好的记录。 I was very surprised, because other ORMs allow such relation quering.
我很惊讶,因为其他ORM允许这种关系查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.