Я использую OctoberCMS на основе Laravel.
Я пытаюсь получить идентификатор из URL и передать его в Scope для фильтрации результатов базы данных.
$ this-> property (‘username’) работает и возвращает имя пользователя из URL.
Но как передать его в модель и в функцию Scope?
Вот руководство, под Динамические Области.
https://octobercms.com/docs/database/model#query-scopes
страница
URL: localhost / пользователь / матовый
Идентификатор: / пользователь /: имя пользователя
Компонент результатов
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');
Изменения, которые я сделал:
полный рабочий пример, который печатает результаты:
$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)),
]);
}
Других решений пока нет …