将变量从组件传递到模型范围 [英] Pass Variable from Component to Model Scope
问题描述
我正在使用基于Laravel的OctoberCMS.
I'm using OctoberCMS based on Laravel.
我正在尝试从URL获取标识符,并将其传递给Scope来过滤数据库结果.
I'm trying to get the identifier from URL and pass it to the Scope to filter database results.
$ this-> property('username')起作用并从URL返回用户名.
$this->property('username') works and returns the username from the URL.
但是如何将其传递给模型并传递给Scope函数?
But how do you pass it to the Model and into the Scope function?
此处是动态范围"下的指南.
Here is the guide, under Dynamic Scopes.
https://octobercms.com/docs/database/model#query-scopes
页面
URL:localhost/user/matt
URL: localhost/user/matt
标识符:/user/:用户名
Identifier: /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)允许变量正确传递.
I found adding ($query, $username = null) allows the variable to pass without error.
但是现在的问题是$ username既是'matt'又是null,并且从不使它返回查询.
But now the problem is that $username is both 'matt' and null at the same time and never makes it to the query return.
// 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
}
推荐答案
在模型库中,您需要一个现场用户:
In a model gallery you need a field user:
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);
}
}
}
然后,当您具有nullchecks时,您可以使用
Then, when you have the nullchecks you can just call it with
$gallery = new Gallery();
$query = $gallery->newQuery()->where('x','y')->whereUser('matt');
我所做的更改:
- 将范围重命名为whereuser而不是apply user,因为这样命名更合乎逻辑.将您的工作应用于永久改变状态的功能
- 添加了一个not is_null()检查,以仅在查询不为null时限制查询.
显示结果的完整示例:
$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)),
]);
}
这篇关于将变量从组件传递到模型范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!