【发布时间】:2018-11-12 17:02:59
【问题描述】:
我有一个问题,user_id 似乎被 Laravel Eloquent ORM 完全忽略了。
鸽子表id user_id name father_id mother_id ringnumber
gender color created_at updated_at landcode
(这些是我的专栏(如果有人知道如何更好地格式化,请告诉我))
我有一个搜索,从中将搜索参数 q 路由到我的 SearchController.php,该函数位于其中:
namespace App\Http\Controllers;
use App\Pigeon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
class SearchController extends Controller
{
public function index()
{
$q = Input::get('query');
$userId = Auth::user()->id;
$pigeons = Pigeon::where([
['user_id', '=', $userId],
['name','LIKE','%'.$q.'%']
])
->orWhere('ringnumber','LIKE','%'.$q.'%')
->sortable()
->paginate(15);
dd($pigeons);
return view('backend.pigeon.pigeonlist')->with('pigeons', $pigeons);
}
}
由于某种原因,这个 Eloquent 查询生成器似乎完全忽略了'user_id', '=', $userId,这是一个重要的部分,因为我只想为当前登录的用户搜索鸽子。
下面是这样一个查询的结果,问题是有各种user_id的鸽子,而不仅仅是一个搜索它们的用户。
LengthAwarePaginator {#259 ▼
#total: 150
#lastPage: 10
#items: Collection {#267 ▼
#items: array:15 [▼
0 => Pigeon {#268 ▶}
1 => Pigeon {#269 ▶}
2 => Pigeon {#270 ▶}
3 => Pigeon {#271 ▶}
4 => Pigeon {#272 ▶}
5 => Pigeon {#273 ▶}
6 => Pigeon {#274 ▶}
7 => Pigeon {#275 ▶}
8 => Pigeon {#276 ▶}
9 => Pigeon {#277 ▶}
10 => Pigeon {#278 ▶}
11 => Pigeon {#279 ▶}
12 => Pigeon {#280 ▶}
13 => Pigeon {#281 ▶}
14 => Pigeon {#282 ▶}
]
}
#perPage: 15
#currentPage: 1
#path: "http://mywebsite.test/pigeon/search"
#query: []
#fragment: null
#pageName: "page"
+onEachSide: 3
}
小记,我从这里得到了一些我的信息:How to create multiple where clause query using Laravel Eloquent?
问题已解决: 首先,我有一个 orWhere 否决了 where 所以这对我来说非常愚蠢。 其次,我真正的问题是我试图仅获取通过此代码工作的当前登录用户的记录:
$pigeons = Pigeon::where('user_id', \Auth::id())
->where(function($query) use ($q) {
$query->where('name', 'LIKE', '%'. $q .'%');
})
->sortable()
->paginate(15);
【问题讨论】:
-
ringnumber中有什么内容?这也是特定于用户的吗? -
不,先生,戒指号码不是特定于用户的,而是特定于鸽子的
-
当你使用
->orWhere你说上面那个是真的,或者这个是真的时,就会出现问题。 -
是的,没错,orWhere 推翻了 where,导致它否定了 user_id
标签: laravel