我有两个相关的模型。我试图在订单中进行搜索,只显示实际搜索结果,而不是找到订单的类别和用户的所有订单。
public function up()
{
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('category_id')->constrained()->cascadeOnDelete();
$table->foreignId('report_id')->constrained()->cascadeOnDelete();
$table->string('time');
$table->string('date');
$table->integer('issue_number');
$table->boolean('status');
$table->text('description')->nullable();
$table->timestamps();
});
}
所以,我想要实现的是以下目标。我想要显示的是:
OrderController.php
public function index()
{
$keyword = request('search') ?? null;
$orders = Order::query()->whereIn('user_id', $user->id)->whereIn('category_id', $category->id)
->orWhere(function ($query) use ($keyword) {
$query->when($keyword, function ($query) use ($keyword) {
$query->where('first_name' , 'LIKE' , "%{$keyword}%");
});
})->latest()->paginate(25);
return view('Admin.orders.index', compact('orders'));
}
订单.php
public function user()
{
return $this->belongsTo(User::class);
}
public function report()
{
return $this->belongsTo(Report::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
如果我说得对,您希望将筛选器应用于相关表。对于这种操作,可以使用雄辩的whereHas
或whereRelation
方法。
$posts = Post::whereHas('comments', function (Builder $query) {
$query->where('content', 'like', 'code%');
})->get();
或
$posts = Post::whereRelation(
'comments', 'created_at', '>=', now()->subHour()
)->get();
comments
是相关列。
有关详细信息,请查看查询关系是否存在。