Laravel: Column not found - laravel

I am trying to set up the following SQL in Laravel.
$projects = DB::table(DB::raw('places, areas, areas_places'))
->select('projects.*')->distinct()
->leftJoin('tags_places as r', 'r.place_id', '=', 'places.place_id')
->leftjoin('tags as t', 't.id', '=', 'r.tag_id')
->join('areas_places as e', 'e.place_id', '=', 'places.place_id')
->join('areas as a', 'a.area_id', '=', 'e.area_id')
However, I keep getting the following error.
Column not found: 1054 Unknown column 'places.place_id' in 'on clause'
The column exists in the database. I've also checked to see if the column is spelled correctly-- it is. So what could I be missing? I am using Laravel Mix version 4.0.7

I figured out what the issue was. I just didn't need the DB::raw statement. This works as expected without problems:
$projects = DB::table('projects')
->select('projects.*')->distinct()
->leftJoin('tags_places as r', 'r.place_id', '=', 'places.place_id')
->leftjoin('tags as t', 't.id', '=', 'r.tag_id')
->join('areas_places as e', 'e.place_id', '=', 'places.place_id')
->join('areas as a', 'a.area_id', '=', 'e.area_id')
IGP's suggestion to check with toSql() was helpful in figuring this out.

Related

How to write SQL Function where YEAR(<date_column_name>) in laravel controller

I want to fetch data from database which has booking year is 2022, and the column I have is tanggal_take whose value format is 'Y-m-d', so I want to use SELECT * FROM table_name WHERE YEAR(tanggal_take) = "2022"; How to write it in laravel controller using Eloquent?
here is my code now
$data = Booking::join('users', 'users.id', '=', 'bookings.id_member')
->join('packages', 'packages.kode_paket', '=', 'bookings.kode_paket')
->where( DB::raw('YEAR(bookings.tanggal_take)'), '=', $request->range )
->get(['bookings.*', 'packages.*', 'users.*']);
The result is 0 but in database i have 4 datas with year 2022. I also already change ->where( DB::raw('YEAR(bookings.tanggal_take)'), '=', $request->range ) to ->whereYear('bookings.tanggal_take', '=', $request->range ) but still 0 result. Any hint? I will also looking for documentation by my self rn. Thanks

Select Specific columns from multiple Table with with() and select ()

I have 2 tables test and goals. One goal has many tests. I would like to fetch data like below.
$tests = test::with('goals')
->where('Goal_id', $goal_id)
->select('test.id as id','goals.Goal_id as goal_id','test.mode as mode')
->get();
But I am getting error Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'goals.Goal_id' in 'field list'
The goals relation is being eager loaded in a separate query so you will not have access to goals.Goal_id in your main query builder, instead you can modify your with() clause to pick specific columns from eager loaded relation as with('goals:Goal_id,another_column')
$tests = test::with('goals:Goal_id')
->where('Goal_id', $goal_id)
->select(['test.id as id','test.mode as mode'])
->get();
This should work:
$tests = DB::table('test')
->select(['test.id as id', 'goals.Goal_id as goal_id', 'test.mode as mode'])
->join('goals', 'goals.id', '=', 'test.goal_id')
->where('Goal_id', $goal_id)
->get();

How to write this SQL query with Laravel elequoent

I tried this in laravel, but it's not working. I can't get it to work it's working when I use it straight on PHPMyAdmin
SELECT service,
count(*) as total_count,
sum(if(status ='Successful',1,0)) as successful_count,
sum(if(status ='Failed',1,0)) as failed_count
FROM `wallet_ledgers`
WHERE operator = "-"
AND user_id = 5
group by service
this is the desired output The way the table should look
You can use DB::raw
Link: Laravel-raw-expressions
$result = DB::table('wallet_ledgers')
->select(DB::raw("service, count(*) as total_count, sum(if(status ='Successful',1,0)) as successful_count, sum(if(status ='Failed',1,0)) as failed_count"))
->where([
[ 'operator', '=', '-'],
['user_id', '=', '5'],
])
->groupBy('service')
->get();

How to remove quotes from SQL query Laravel?

I have the following query:
$this->data = \DB::table('months')->select(DB::raw("months.id, COUNT(transactions.id) as total"))
->leftJoin('transactions', function($join)
{
$join->on('months.id', '=', DB::raw('MONTH(created_at)'))
->on('transactions.doctor_id', '=', $this->user_id);
})
->groupBy('months.id')
->get();
It involks an error on line ->on('transactions.doctor_id', '=', $this->user_id);. It added single quotes for variable $this->user_id.
How to avoid this eroros:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '2' in
'on clause' (SQL: select months.id, COUNT(clients.id) as total
from `months` left join `clients` on `months`.`id` = MONTH(created_at)
and `clients`.`doctor_id` = `2` group by `months`.`id`)
You can try to use DB:raw like this:
->on('transactions.doctor_id', '=', DB::raw($this->user_id));

How to use multiple 'where' clause with multiple tables with Eloquent ORM?

I have a database query with multiple 'JOIN' statements in my Laravel application, but I don't know how to correctly add a where clause to it.
Here is my function:
return Topic::join('blogs', 'topics.blog_id', '=', 'blogs.id')
->join('blog_subscriptions as us', function ($j) use ($userId){
$j->on('us.blog_id', '=', 'blogs.id')
->where('us.user_id', '=', $userId);
})
->take(Config::get('topic.topics_per_page'))
->offset($offset)
->get(['topics.*']);
I would like to add a 'where' clause to the 'topics' table - so I add a line where('rating', '>', 1), after "Topic::", so the code is like this:
Topic::where('rating', '>', 1)
->join('blogs', 'topics.blog_id', '=', 'blogs.id')
->join('blog_subscriptions as us', function ($j) use ($userId){
$j->on('us.blog_id', '=', 'blogs.id')
->where('us.user_id', '=', $userId);
})
->take(Config::get('topic.topics_per_page'))
->offset($offset)
->get(['topics.*']);
but it only leads to an error:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'rating' in where clause is ambiguous (SQL: select topics.* from topics inner join blogs on topics.blog_id = blogs.id inner join blog_subscriptions as us on us.blog_id = blogs.id and us.user_id = 1 where rating > 1 limit 2 offset 0)
As the error message says, the column rating is ambiguous. Meaning SQL can't tell which column you mean because there might be another one in your join that's named rating as well.
In this situation it helps to clarify in which table the field is. This is simply done by using the [table].[field] syntax
where('topics.rating', '>', 1)

Resources