items (id, name, description, subcategory_id, sublocation_id)
categories (id, name)
subcategories (id, name, category_id)
locations (id, name)
sublocations (id, name, location_id)
I am trying to implement a search feature for a laravel 5.4 application. I am taking the following user inputs in order to run a search: 1) The search string 2) Category ID 3) Location ID.However, these three inputs reside in 3 different tables. So in conventional SQL, to get all the items having category_id = 1 and location_id = 1, I would have written a statement like this:
SELECT * FROM `items` WHERE name LIKE 'A%' AND subcategory_id IN (SELECT id FROM sub_categories WHERE category_id = '1') AND sublocation_id IN (SELECT id FROM sub_locations WHERE location_id = '1')
Models:SubCategory.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SubCategory extends Model
{
protected $fillable = [
'name', 'category_id',
];
public function category(){
return $this->belongsTo(Category::class);
}
}
Category.php<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = [
'name',
];
public function subcategories(){
return $this->hasMany(SubCategory::class);
}
}
Location.php & Sublocation.php models are pretty much the same as these two so I didn't post them here.How can I use hasManyThrough() relationship in both Category and Location models to get all the $items? Or is there any other simple way to achieve what I want?
via Eisenheim