我正在使用基于 Laravel 的 OctoberCMS。
我正在尝试从 URL 获取标识符并将其传递到范围以过滤数据库结果。
$this->property('username') 起作用并从 URL 返回用户名。
但是如何将它传递给模型和范围函数呢?
这是动态范围下的指南。
https://octobercms.com/docs/database/model#query-scopes https://octobercms.com/docs/database/model#query-scopes
Page
URL:本地主机/用户/马特
标识符:/用户/:用户名
结果部分
public function init()
{
// get username from url
$username = $this->property('username'); //matt
// pass username to scope
Gallery::applyUser($username);
}
画廊模型
// return results that match username
public function scopeApplyUser($query, $username)
{
return $query->where('username', $username);
}
Error
Missing argument 2 for MyVendor\Gallery\Models\Gallery::scopeApplyUser()
解决方案?
我发现添加 ($query, $username = null) 允许变量无错误地传递。
但现在的问题是 $username 同时为 'matt' 和 null,并且永远不会进入查询返回。
// return results that match username
public function scopeApplyUser($query, $username = null)
{
print $username; //prints matt
if ($username == null) { print 'null'; } //prints null
return $query->where('username', $username); //returns null
}