I have 2 tables, projects and jobs. jobs has a column called project_id. In Laravel 5.2 I want to run a search that will return all jobs which belong to a project of a given search term. This SQL works:
SELECT jobs.*, projects.name FROM jobs INNER JOIN projects ON jobs.project_id = projects.id WHERE projects.name LIKE "%$keyword%"
In my Job.php model I have created a scope method, which errors:
public function scopeSearch($query, $keyword)
{
if ($keyword != '') {
$query->where(function($query) use ($keyword) {
$query->where('projects.name', 'LIKE', '%' . $keyword . '%')->join('projects', 'jobs.project_id', '=', 'projects.id');
});
}
return $query;
}
This produces the error:
Column not found: 1054 Unknown column 'projects.name' in 'where
clause' (SQL: select * from jobs where (projects.name LIKE
%test%))
In my JobsController.php I have:
$searchResults = Job::Search($searchTerm)->get();
The parameter $query in where(function($query) is not the $query that you passed in public function scopeSearch($query, $keyword)
You can either remove it with just the query like below (as #Rob mentioned)
public function scopeSearch($query, $keyword)
{
if ($keyword != '') {
$query->where('projects.name', 'LIKE', '%' . $keyword . '%')->join('projects', 'jobs.project_id', '=', 'projects.id');
}
return $query;
}
or you need to include the $query in use()
$query->where(function() use ($keyword, $query)
Related
I want to apply search on the item members which is associated with the item.
I've members relation on my Item model like this
public function members()
{
return $this->hasManyDeep(
'App\Models\Users\TeamMember',
['App\Models\Users\Team'],
[['teamable_type', 'teamable_id'], 'team_id'],
['id', 'id']
);
}
I've done this code for apply search on items on the bases of item's members
$items = Item::query();
->where('title', 'Like', '%' . $keyword . '%')
->with('members')
->orWhereHas('members', function ($query) use($keyword) {
$query->from('users')->where('name', 'Like', '%' . $keyword . '%');
})->get();
this relation will be return an array of members. Now It's giving me error called -
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'team_members.team_id' in 'on clause' (SQL: select * from `items` and `title` Like %test% or exists
I have two tables, product_template and shorttitles.
A product can have multiple shorttitles, depending on language
A product has a primary title (called mmac_ebay_titolo), and a shorttitle has a name, that is the title in different language.
My goal is to filter, depending on post input, the shorttitles title and the product_template title with the string posted.
if no filter string is passed, all works fine.
The shorttitles model has this relation:
public function prodotto()
{
return $this->belongsTo('App\Product', 'product_id', 'id');
}
The product_template model has this relation:
public function shorttitle()
{
return $this->hasMany('App\ShortTitle', 'product_id', 'id');
}
But I'm stuck with the code below:
$m = self::MODEL;
$query = $m::select("*");
$data["data"] = $query
->with(["prodotto" => function ($q) use ($params) {
$q->select("id", "name", "mmac_ebay_titolo")
->where("name", "like", "%" . $params["search"] . "%");
}]
)->where("lang_id", "=", 1)
->offset($start)
->limit($limit)
->orderBy("id", "asc")
->get();
This query returns all shorttitles... with "prodotto" = null if the subquery doesn't match the where clause. Why?
After this, I would filter the main shorttitles table with this:
$m = self::MODEL;
$query = $m::select("*");
$data["data"] = $query
->with(["prodotto" => function ($q) use ($params) {
$q->select("id", "name", "mmac_ebay_titolo")
->where("mmac_ebay_titolo", "like", "%" . $params["search"] . "%");
}]
)->where("lang_id", "=", 1)
->where("name", "like", "%" . $params["search"] . "%")
->offset($start)
->limit($limit)
->orderBy("id", "asc")
->get();
I want to reproduce this query:
Select
s.name,
p.name,
p.mmac_ebay_titolo
From
mmac_brx_ebay_shorttitles s Inner Join
product_template p On s.product_id = p.id
where lang_id = 1
and
(
s.name like '%PIGNONE%'
or
p.name like '%PIGNONE%'
or
p.mmac_ebay_titolo like '%PIGNONE%'
)
How can I achieve this?
Thanks!
try this query:
$products = $query->join('product_template','mmac_brx_ebay_shorttitles.product_id','=','product_template.id')
->where(function ($query) {
$query->Where('mmac_brx_ebay_shorttitles.name','like','%PIGNONE%')
->orWhere('product_template.name','like','%PIGNONE%')
->orWhere('product_template.mmac_ebay_titolo','like','%PIGNONE%');
})->where('your_table_name.lang_id',1)
->select('mmac_brx_ebay_shortitles.name','product_template.name','product_template.mmac_ebay_titolo')
->paginate(10);
I have a table with input fields that act as filters. There are values from Orders table and Users table which has a relationship.
e.g.:
Order Id | User Full Name | Order Price | Date |
[order filter] [user name filter] [order date filter]
How can I filter a value from a users table via relationship?
This returns error of course:
public function name($name)
{
return $this->builder->where('name', 'LIKE', '%$name%')->orWhere('surname', 'LIKE', '%$name%');
}
Error:
QueryException in Connection.php line 770:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name' in 'where clause' (SQL: select count(*) as aggregate from `orders` where (`name` LIKE %$name% or `surname` LIKE %$name%))
You can add the condition directly to your query builder or create a scope.
Add this to your Order model.
public function scopeFilterUser($query, $name)
{
return $query->whereHas('user', function ($q) use ($name) {
$q->where('name', 'like', "%{$name}%")
->orWhere('surname', 'like', "%{$name}%");
});
}
Use it like so
$orders = Order::filterUser($name)->get();
Apply the condition directly.
$orders = Order::whereHas('user', function ($query) use ($name) {
$query->where('name', 'like', "%{$name}%")
->orWhere('surname', 'like', "%{$name}%");
})->get();
Edit : Based on your filter methods.
public function name($name)
{
return $this->builder->whereHas('user', function ($q) use ($name) {
$q->where('name', 'like', "%{$name}%")
->orWhere('surname', 'like', "%{$name}%");
});
}
I have a query that Im trying to retrieve. Its suppose to get a listings information with its trips and location details.
This is how Im calling the query inside the Destinations controller:
public function destinations($id) {
$destination = Destination::findOrFail($id);
$listingGuides = Listing::findGuidesTrips($destination)
->with('locations')
->withCount('trips')
->get();
return view('destinations.index', compact('listingGuides');
}
And the findGuidesTrips method is inside the Listings Model:
public static function findGuidesTrips($destination) {
$query = self::query()
->leftJoin('trips', 'listing_id', '=', 'listings.id')
->addSelect(
\DB::raw('listings.name,listings.slug,listings.type,listings.id,MIN(trips.cost) as starting_price')
)
->groupBy('listings.id');
$query = self::query()
->leftJoin('locations', 'listing_id', '=', 'listings.id')
->addSelect(
\DB::raw('locations.longitude as longitude')
)->addSelect(
\DB::raw('locations.latitude as latitude')
);
$query = $query->whereHas('locations',function($query) use ($destination) {
$query->where('region', 'like', $destination->location)->orWhere('country', $destination->location);
});
return $query;
}
This is what I get back:
As you can see, I have 2 $query = self::query() quires, but only one is being called (the bottom one). Its ignoring the top self::query.
I was just wondering how would I go about combining these 2 leftJoin queries into one perhaps? Or is there a better way of doing this query?
( I tried doing this: )
$query = self::query()
->leftJoin('trips', 'listing_id', '=', 'listings.id')
->addSelect(
\DB::raw('listings.name,listings.slug,listings.type,listings.id,MIN(trips.cost) as starting_price')
)
->leftJoin('locations', 'listing_id', '=', 'listings.id')
->addSelect(
\DB::raw('locations.longitude as longitude')
)->addSelect(
\DB::raw('locations.latitude as latitude')
)->groupBy('listings.id');
But it gives me Integrity constraint violation: 1052 Column 'listing_id' in on clause is ambiguous error
As stated by #Tim Lewis and #Niklesh, all I had to do was:
trips.listing_id for first query and locations.listing_id for second.
Here is the final query:
public static function findGuidesTrips($destination) {
$query = self::query()
->leftJoin('trips', 'trips.listing_id', '=', 'listings.id')
->addSelect(
\DB::raw('listings.name,listings.slug,listings.type,listings.id,MIN(trips.cost) as starting_price')
)
->leftJoin('locations', 'locations.listing_id', '=', 'listings.id')
->addSelect(
\DB::raw('locations.longitude as longitude')
)->addSelect(
\DB::raw('locations.latitude as latitude')
)->groupBy('listings.id');
$query = $query->whereHas('locations',function($query) use ($destination) {
$query->where('region', 'like', $destination->location)->orWhere('country', $destination->location);
});
return $query;
}
I'm trying to concat two columns from different tables into one single column.
$user = User::with(array('Person'=>function($query){
$query->selectRaw('CONCAT(prefix_person.name, " - ", prefix_user.code) as name, prefix_user.id');
}))->lists('name', 'id');
In my person class I have this method:
public function User()
{
return $this->hasOne('User');
}
And in my user class I have this one:
public function Person()
{
return $this->belongsTo('Person', 'person_id');
}
I get the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name' in 'field list' (SQL: select `name`, `id` from `prefix_user`)
When I tried
$user = User::with(array('Person'=>function($query){
$query->selectRaw('CONCAT(prefix_person.name, " - ", prefix_user.code) as name, prefix_user.id')->lists('name', 'id');
}));
I got this error:
I have used the selectRaw a couple of times, but never needed it into a with (join).
The issue is that Eloquent will first query the users table, and only after, the persons table, so one query is not aware of the other and thus concatenating will not work.
You can use the Query Builder to do this using a join. It will be something like it:
$user = DB::table('users as u')
->join('persons as p', 'p.id', '=', 'u.person_id')
->selectRaw('CONCAT(p.name, " - ", u.code) as concatname, u.id')
->lists('concatname', 'u.id');
EDIT:
And, as suggested by #michel-ayres comment, as long as you have an acessor to the field:
public function getFullNameAttribute() {
return $this->attributes['name'] . ' - ' . $this->attributes['code'];
}
you can use your own model to perform the join and listing:
User::join('person','person.id','=','user.person_id')
->select('person.name', 'user.code', 'user.id')
->get()
->lists('full_name', 'id');
You can solve it simply by using simple query,
User::join('persons as p', 'p.id', '=', 'users.person_id')
->get([
'id',
DB::raw('CONCAT(p.name,"-",users.code) as name')
])
->lists('name', 'id');
Or, see another way
User::join('persons as p', 'p.id', '=', 'users.person_id')
->select(
'id',
DB::raw('CONCAT(p.name,"-",users.code) as name')
)
->lists('name', 'id');
You can solve it by using this sample query
->when($request->value != null, fn ($q) => $q->where(DB::raw("CONCAT(col1,'',col2)"), '=', '' . $request->value.
''))