Php 将变量从组件传递到模型范围
我正在使用基于Laravel的OctoberCMS 我试图从URL中获取标识符,并将其传递给作用域以过滤数据库结果 $this->property('username')工作并从URL返回用户名 但是如何将其传递给模型和范围函数呢 下面是指南,在动态范围下 页面 URL:localhost/user/matt 标识符:/user/:用户名 结果组件Php 将变量从组件传递到模型范围,php,laravel,laravel-5,octobercms,Php,Laravel,Laravel 5,Octobercms,我正在使用基于Laravel的OctoberCMS 我试图从URL中获取标识符,并将其传递给作用域以过滤数据库结果 $this->property('username')工作并从URL返回用户名 但是如何将其传递给模型和范围函数呢 下面是指南,在动态范围下 页面 URL:localhost/user/matt 标识符:/user/:用户名 结果组件 public function init() { // get username from url $username = $th
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
}
在模型库中,您需要现场用户:
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');
我所做的改变:
- 将作用域重命名为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)),
]);
}
$gallery=newgallery();
$query=$gallery->newQuery()->where('x','y')->whereUser('matt');
$results=$query->get();
foreach(结果为$galleryItem){
echo$galleryItem->getKey()。'具有:
;
回波转储([
“型号”=>$galleryItem,
“方法”=>get_类方法(get_类($galleryItem)),
]);
}
!is_null显示$username不为null,但我得到了解析错误:语法错误,意外的“$table”(T_变量),期望函数(T_函数)。$query给出了502个坏网关。它们只是占位符。。您只需要将作用域函数注入到您的模型中。我已将作用域放入我的模型中,然后将变量传递给它。它工作,变量打印,但是当我在查询中返回它时,它是空的。它怎么能同时有值和为null?它不是。您不了解查询生成器是如何工作的。让我帮你更新一下。我不知道在哪里使用$gallery=new gallery()。在OctoberCMS中,您可以拖放记录列表,并从模型中选择范围函数。然后将$type传递给作用域,并在作用域内返回$query。现在,记录列表被该范围过滤。我正在从一个组件传递它。请尝试使用下面的$username=$\u get['username']从url获取属性;而不是$username=$this->property('username');您将了解真正可以访问的属性。旁注:还可以尝试使用Input::get(“url_param”)
@Meysam返回null。