Need help building query laravel 5.2 - php

I'm trying to get rings from the database. but only filter is the homepage is 1 or 0.
I only need the rows where homepage is 1.
This is what i tried
$ringen = RingKoppelCategory::with('ringen')->get()->where('homepage', '=' , 1);
returns null
And when i put the ->get() at the end of the query builder it checks the ringkoppelcategory table for a homepage which is not what i want it to do.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'homepage' in 'where clause' (SQL: select * from `ringkoppelcategory` where `homepage` = 1
I need to get the rings relationship from the ringkoppelcategory, but only the rings where the homepage is 1.

You need to use a function to pass along a where within your with.
$ringen = RingKoppelCategory::with(['ringen' => function ($query) {
$query->where('homepage', '=' , 1);
}])->get();
More information is found in the documentation

I think you need to use the following query
$ringen = RingKoppelCategory::whereHas('ringen', function ($query) {
$query->where('homepage', '=', 1);
})->get();
Check Querying Relationship Existence section at documentation

Related

Laravel filtering - get the last created entry from the DB which has a specific ID

For this data (from a table called status_student):
I want to do some filtering. This table is a pivot table and I want to return a record from a base table only if the latest created object has a specific status_id.
For example, if I filter for status_id = 1, I shouldn't get any object for those two rows.
Here's my query for filtering:
$query = Student::whereHas('statusuri', function($q) use ($status) {
$q->orderBy('status_student.data_sfarsit', 'desc')->where('status_id', '=', $status);
});
statusuri From Student:
public function statusuri()
{
return $this->belongsToMany(Status::class, 'status_student')
->withPivot('id', 'data_inceput', 'data_sfarsit', 'document', 'status_id', 'stare_stagiu_id')
->withTimestamps();
}
My query works, but it returns an object if I filter for a status_id of 1 and of 6 too. I only want to return an object for filtering with status_id = 6 (because that is the latest status).
I tried modifying my query like this:
$query = Student::whereHas('statusuri', function($q) use ($status) {
$q->orderBy('status_student.data_sfarsit', 'desc')->first()->where('status_id', '=', $status);
});
but then it didn't work, and I think I know the reason.
first() returns an instance of another type (after an inner join, basically), which doesn't have a status_id. So I shouldn't use it this way. Also, it returns an object, not a Query Builder instance anymore.
The error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'students.id' in 'where clause' (SQL: select * from `statusuri` inner join `status_student` on `statusuri`.`id` = `status_student`.`status_id` where `students`.`id` = `status_student`.`student_id` order by `status_student`.`data_sfarsit` desc limit 1)
So, how can I make that query filter my latest created DB row with a specific status_id?
Thanks.
//Example:
For student_id = 1 as in the picture:
if status_id = 1:
query returns nothing
if status_id = 6:
query returns the student
Explanation:
$status_id is provided through a HTML form, and I want to return that specific student if the last status known is equal to this $status_id.
My approach was filtering with latest(id) so I get the latest entry on the first row, then getting the first entry, then doing a where clause on the status_id. But it doesn't work because first() returns an object, not a QueryBuilder anymore.

Count in update query doesn't work in Laravel

public function increment($id)
{
$this->model->where("id",'=', $id)->update(['rating'=> DB::raw('count+1')]);
}
I am getting the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'count' in
'field list' (SQL: update news set rating = count+1, updated_at
= 2019-04-13 08:12:51 where id = 5)
I also tried
->update(['rating'=>'count+1']);
You are not telling the query builder on which table you are performing the query, so DB::raw('count+1') makes no sense.
You can try to use the eloquent increment method like this:
$this->model->where("id", $id)->increment('rating');
Thanks #Tharaka removed the extra call to save().

laravel join tables column not found

Hi I am building an application and I have a table for example projects and then settings. However they do not have a foreign key with each other and i have other tables such as tasks, clients etc. And these have settings which I am planning to save in the settings table.
The settings table has a column of type, which i will fill with the related model name e.g. project. Anyway when i am fetching a project I also want to fetch a the settings where the type = project. So I've tried to do a table join instead however this has thrown the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'project' in 'on clause' (SQL: select * from `projects` inner join `settings` on `type` = `project`)
The code I've used is as follows:
return \Project::()->join('settings', 'type', '=', 'project')->get();
I see what the problem is, its looking for a column called project however there isn't one. I suppose what i want to do is use eloquent and a query function to join the table and then query the settings table where type = project. does anyone know how i can do this?
update from burak answer
I've tried to put this in my model as so so
settings.php
public function sprint() {
return \Setting::where('type', '=', 'sprint')->get();
}
and sprint.php
public function settings() {
return \Setting::where('type', '=', 'sprint')->get();
}
however I get this error Call to undefined method
Illuminate\Database\Eloquent\Collection::addEagerConstraints() and I've called it using this method:
return Sprint::with(['settings'])->get();
what have i done wrong here?
Because you are not referencing the table names and you are comparing columns. Instead, what you need is a where statement within your join condition to compare with a value.
return DB::table('projects')
->join('settings', function ($join) {
$join->where('settings.type', '=', 'project');
})->get();
But you should better get settings and projects one by one as all identical settings columns will be added to your projects rows which is not good.
$data = [];
$data['projects'] = Project::all();
$data['settings'] = Settings::where('type', '=', 'project')->first();
return $data;
Update:
Within your Sprint model
public function scopeWithType()
{
return static::join('settings', function ($join) {
$join->where('settings.type', '=', 'sprint');
});
}
Then within the controller
Sprint::withType()->get();
I have not tried but I think this is what you want. This is how we do subqueries or query joins with where clause.
return \Project::join('settings', function($q) {
$q->where('type', '=', 'project');
})->get();
your code looks for records matching project field in the table settings and type field in the project table, which is not the case.

Filter on laravel pivot table

I have two tables in Laravel connected with a pivot table. The two tables are users and roles, and the pivot table is called role_user. The pivot table also contains two extra fields: start and stop. This way I can track which roles a user has had in the past.
Now I want to create a query that gets all users who currently have role_id = 3.
First I had used WherePivot, but apparently that is bugged.
I have now made the following query using Eloquent:
Role::with('User')
->where('id', '=', '3')
->where('role_user.start', '<', date('Y-m-d'))
->where('role_user.stop', '>', date('Y-m-d'))
->whereHas('users', function($q){
$q->where('firstname', 'NOT LIKE', '%test%');
})
->get();
But somehow I am getting an error that the column start of the pivot table cannot be found. But I can confirm in PHPMyAdmin that the column is there.
This is the entire error:
Illuminate \ Database \ QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'klj_role_user.start' in 'where clause' (SQL: select * from `klj_roles` where `id` = 3 and `klj_role_user`.`start` < 2014-06-02 and `klj_role_user`.`stop` > 2014-06-02 and (select count(*) from `klj_users` inner join `klj_role_user` on `klj_users`.`id` = `klj_role_user`.`user_id` where `klj_role_user`.`role_id` = `klj_roles`.`id` and `firstname` NOT LIKE %test%) >= 1)
Can someone tell me if I am doing something wrong or give me a hint where I should be looking now?
The error is telling you that you are missing the start column in your pivot table klj_role_user. What you should do is create the column. If the column is already there, ensure you are using the correct database.
I've also simplified your query a little bit. You don't really need a whereHas because you aren't trying to limit your roles by the users associated, but by the id, which in this case, you are using 3. A with() would work perfectly fine and wherePivot() seems to be working fine for me when used in conjunction with with().
$role = Role::with(array('users' => function($q)
{
$q->wherePivot('start', '>', date('Y-m-d H:i:s'));
$q->wherePivot('stop', '<', date('Y-m-d H:i:s'));
$q->where('firstname', 'NOT LIKE', '%test%');
}))->find(3);
foreach($role->users as $user) {
echo $user->firstname;
}

Laravel STDDEV with LIMIT

I'm trying to get the AVG() and the STDDEV_SAMP() on subset of data using Laravel.
So I've tried
//Data from which I want to calculate the AVG and STDDEV_SAMP()
//Limit the query to certain values
$subquery = TableAModel::join('TableB','TableA.TableB_id','=','TableB.id')
->select('Factor1')
->whereraw('conditionA <= 10')
->orderBy('DateTimeCode', 'desc')
->take('5')
->toSql();
//My aggregate functions
$aggregates = 'AVG(TableA.Factor1) as Factor1,
STDDEV_SAMP(TableA.Factor1) as Factor1_SD';
//My final query that should return the average and SD
$AVG_SD = \DB::table(\DB::raw(" ($subquery) as sub "))->select(\DB::raw("$aggregates"))->first()->toArray();
//it should return something like array([Factor1] => The_average, [Factor1_SD] => The_SD)
However, it throws me "Column not found: 1054 Unknown column 'TableA.Factor1' in 'field list'". If I try to select('*'), it throws me "Duplicate columns id".
I don't really have any experience with this but, it looks to me like your creating a view and from that view you want to find the STD and AVG of Factor1. But you say AVG(TableA.Factor1) as Factor1, I don't think TableA would be the table name for DB::table(\DB::raw(" ($subquery) as sub ")) so its not finding Factor1 because its can't find the table. would the table not be called sub.
I have no idea if this is the case or not, but hope it helps, also would've left a comment but I don't have the rep yet :(.

Categories