問題描述
我一直在嘗試在 laravel' eloquent 中創建我自己的可鏈接方法,但我遺漏了一些東西并且不確定是什么.這聽起來可能有點瘋狂,但請查看下面我的函數,以更好地了解我想說的內容.
I have been trying to create my own chainable method in laravel' eloquent but I'm missing something and not sure what. This may sound a little bit nuts but have a look at my function below to get a better idea of what I'm trying to say.
class Post extends Eloquent{
public static function custom_wh($data){
return static::where_in('categories_id', $data, 'AND');
}
}
//this works fine
$posts = Post::custom_wh(array(1, 2, 3))->get();
//but this says custom_wh is not defined in the query class
$posts = Post::where_in('tags', array(2, 3, 4), 'AND')->custom_wh(array(1, 2, 3))->get();
如果我理解正確,那么我的方法沒有資格在另一個方法之后鏈接?所以我想我的問題是如何在我的模型中創建一個可鏈接的方法?
if I understand correctly then my method is not eligible to chain after another method? So I guess my question is how can I create a chainable method in my model?
PS 我已經查看了 laravel 的查詢構建器類,在那里我看到可鏈接的方法返回該對象的實例,但除了我在代碼中完成的方式之外,我找不到返回該對象的方法多于.任何形式的建議或建議都非常感謝.提前致謝.
P.S I have looked into the laravel's query builder class where I have seen that the chainable methods returns the instance of that object but I couldn't find a way to return the object other than the way I've done in the code above. Any kind of suggestion or advice is highly appreciated. Thanks in advance.
推薦答案
您可以在 Laravel 中使用查詢范圍"來做到這一點.您可以在此處找到文檔.
You can do that in Laravel with the "query scopes". You can find the doc here.
你只需要寫一個帶有前綴scope
的函數,你就可以像其他查詢構建器一樣鏈接這個方法:
You just have to write a function with the prefix scope
and you will be able to chain this method like the other query builder ones :
class Post extends Eloquent {
public function scopeWhereCategories($query, $categories)
{
return $query->whereIn('categories_id', $categories, 'AND');
}
}
$posts = Post::whereCategories([1, 2, 3])->get();
$posts = Post::orderBy('date')->whereCategories([1, 2, 3])->take(5)->get();
這篇關于在 Laravel 中創建一個可鏈接的方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!