gpt4 book ai didi

Laravel 条件 where with eloquent

转载 作者:行者123 更新时间:2023-12-02 00:28:47 25 4
gpt4 key购买 nike

我有传递简单参数的基本功能:

public function template($person)
{
$offers = Offer::where([
['person', $person],
['published', true],
])
->orderBy('created_at','desc')->paginate(9);
}

现在我想让它成为条件,是否有参数:

public function template($person)
{
if ($person) {
$offers = Offer::where([
['person', $person],
['published', true],
])
->orderBy('created_at','desc')->paginate(9);
} else {
$offers = Offer::where([
['published', true],
])
->orderBy('created_at','desc')->paginate(9);
}
}

这行得通,但这不是一个好的做法,如果我有更多参数怎么办:

public function template($person, $country, $region) {
....
}

然后我将不得不提出多个案例。 eloquent有没有什么辅助函数可以让它更简单?

最佳答案

使用 when 函数作为条件以获得更好的代码风格 see more

$offers = Offer::when($person,function($query,$person) {
return $query->where('person',$person);
})->where('published', true)
->orderBy('created_at','desc')->paginate(9);

关于Laravel 条件 where with eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52759680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com