我正在使用基于Laravel的OctoberCMS。
我正在尝试从URL获取标识符并将其传递给Scope以过滤数据库结果。
$ this-> property('username')可以运行并从URL返回用户名。
但是如何将它传递给模型并进入Scope函数?
以下是动态范围下的指南。
https://octobercms.com/docs/database/model#query-scopes
网页
网址:localhost / user / matt
标识符:/ user /:username
结果组件
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);
}
错误
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
}
答案 0 :(得分:1)
在模型库中,您需要一个现场用户:
class Gallery extends Model {
/** these are just placeholder variables you should be recognising these from your own model.!**/
protected $table = 'gallery';
protected $guarded = ['*'];
protected $fillable = ['username'];// Make sure this also is in the database!!
public scopeWhereUser($query, $user = null) {
if(!is_null($user)) { // Only do something if the username is provided!
$query->where('username',$user);
}
}
}
然后,当你有零检查时,你可以用
来调用它 $gallery = new Gallery();
$query = $gallery->newQuery()->where('x','y')->whereUser('matt');
我所做的改变:
打印结果的完整工作示例:
$gallery = new Gallery();
$query = $gallery->newQuery()->where('x','y')->whereUser('matt');
$results = $query->get();
foreach($results as $galleryItem) {
echo $galleryItem->getKey() . ' is having:<BR/>';
echo dump([
'model'=>$galleryItem,
'methods' => get_class_methods(get_class($galleryItem)),
]);
}