Eloquent column alias in lumen5.8 - laravel-5

How to give alias in replated table hasMany relationship.
Controller
$templates = UserMaster::where ( 'INACTIVE', '=', 0 )->with('contact')->get ();
Model
public function contact(){
return $this->hasMany(\App\Models\Contact::class,'CONTACT_ID');
}
I can try this code my but give error
$templates = UserMaster::where ( 'INACTIVE', '=', 0 )->with('contact as CONTACT')->get ();
So how give alias in with query?
Thank you

Related

how to join table in laravel

I have 2 tables
lets say the 1st one have something like id_teacher_a, id_teacher_b
the 2nd table have the detailed information from table 1 (teacher name, teacher address, etc)
i want to show only the teacher name, so how to join them?
my controller
$data['getid'] = Classroom::select(
'classroom.id',
'teacher.id as tchr_id',
'teacher.name as tchr_name'
)
->join('teacher', 'classroom.teacher_id', '=', 'teacher.id')
->first();
when i want to show table of classroom it would be like
#classroom id #teacher_name_a #teacher_name_b
1 a b
The following should work just fine:
DB::table('classrooms')
->join('teacher as ta', 'ta.id', '=', 'classrooms.id_teacher_a')
->join('teacher as tb', 'tb.id', '=', 'classrooms.id_teacher_b')
->select([
'classrooms.id as classroom_id',
'ta.name as teacher_name_a'
'tb.name as teacher_name_b'
])->get();
Alternatively if you have the following to your Classroom model:
class Teacher extends Model
{
public function teacherA()
{
return $this->belongsTo(Teacher::class, 'id_teacher_a');
}
public function teacherB()
{
return $this->belongsTo(Teacher::class, 'id_teacher_b');
}
}
Then you can also do:
Classroom::query()
->with(['teacherA', 'teacherB'])
->map(function ($classroom) {
return [
'classroom id' => $classroom->id,
'teacher_name_a' => $classroom->teacherA->name,
'teacher_name_b' => $classroom->teacherB->name
];
});

Use Where in QueryBuilder - Laravel

I have a table Products(id,category_id,name);
I want to get a result like this query:
SELECT * FROM Products WHERE category_id=$category_id OR $category_id=0;
When I assign $category_id with 0 value => above query will return all records.
How do I write that query in Laravel?
I've try this:
Products::where(function($query) use ($category_id){
$query->where("category_id",$category_id)
->orWhere($category_id,0)
})->get();
But, Error:
It look like:
SELECT
*
FROM
`products`
WHERE
( `product_category_id` = 0 OR `0` = 0 )
And Print Error: Column not found: 1054 Unknown column '0' in 'where clause'
How to fix: '0' = 0 to 0 = 0?
Thanks!
Use when():
$products = Product::when($categoryId, function ($query, $categoryId) {
$query->whereCategoryId($categoryId);
})->get();
This method will call the function only if the condition is truthy. You could achieve the same thing with simple if statement:
$products = Product::query();
if ($categoryId) {
$products->whereCategoryId($categoryId);
}
$products = $products->get();
What you gain by using when() is that you don't break the chain, so you can use conditional query changes in one expression. It's useful if you want to just return it, for example.
use it
Products::where(function($query) use ($category_id){
$query->where("category_id",$category_id)
->orWhere("category_id",0);
})->get();
what's wrong with your code is this:
->orWhere($category_id,0)
you made the column part as variable.
try this code:
Products::where(function($query) use ($category_id){
return $query->where("category_id", $category_id)
->orWhere("category_id", 0);
})->get();
$product = new Products;
if ($category_id != 0) {
$product = $product->where("category_id", $category_id);
}
$products = $product->get();

Laravel: multiple where clauses in a many-to-many relationship

I am not able to create this sql query on laravel:
select * from `events_theatre` where
event_id IN (
select id from events where (`events`.`id` = `events_theatre`.`event_id` and `user_id` = 1 and `event_type` ='theatre') and `events`.`deleted_at` is null
)
or event_id IN (
select id from events inner join events_managers on events.id = events_managers.event_id and events_managers.user_id = 1
)
and `events_theatre`.`deleted_at` is null
The Events_Theatre model has this relationship:
public function event()
{
return $this->hasOne('App\MyEvent', 'id');
}
While the MyEvent model has this relationship:
public function managers()
{
return $this->belongsToMany('App\User', 'events_managers', 'event_id', 'user_id');
}
Pratically an Events_Theatre model is an Event model, and an Event model may have many managers but just 1 admin.
I need to get that Events_Theatre (and their MyEvent) whose user is an admin or one of the managers.
I tried with this eloquent query:
$list = App\Events_Theatre::whereIn('event_id', function ($query) {
$query
->where(['user_id' => Auth::id(), 'event_type' => 'theatre'])
->orWhereHas('managers', function ($query) {
$query->where('user_id', Auth::id());
});
});
But I get this sql query:
select * from `events_theatre` where
exists (
select * from `events` where (
`events`.`id` = `events_theatre`.`event_id` and `user_id` = 1 and `event_type` = 'theatre'
) or exists (
select * from `users` inner join `events_managers` on `users`.`id` = `events_managers`.`user_id` where `events_managers`.`event_id` = `events`.`id` and `user_id` = 1
)
and `events`.`deleted_at` is null
) and `events_theatre`.`deleted_at` is null
But its wrong. How can I solve this?
Thanks
UPDATED
I got the answer. This is the eloquent code I used:
$list = Events_Theatre::whereHas('event', function ($query) {
$query
->where(['user_id' => Auth::id(), 'event_type' => 'theatre']);
})->orWhereHas('event', function ($query) {
$query
->whereHas('managers', function ($query) {
$query->where('user_id', Auth::id());
});
})->get();
You can try has method
App\Events_Theatre::has('event')->orhas('managers')->get();

Eloquent / Laravel - Putting a WHERE Clause on a Reference Table With Chained Relationships

I have the following relationship functions in my Job model:
public function resourceTypes(){
return $this->belongsToMany('ResourceType', 'job_requests');
}
public function resources(){
return $this->belongsToMany('Resource', 'jobs_resources')->withPivot('flow_type', 'resource_type_id');
}
I am able to get an object with data from both of the above relationships using:
$job = Job::findorfail($projectId);
$result = $job->with('resources.resourceTypes')->get();
I would like to put a where clause on the jobs_resources pivot table - specifically on the column flow_type.
How would I do this?
Try something like this:
$job = Job::with('resources' => function($q) {
$q->with('resourceTypes')->where('flow_type',2);
})->findorfail($projectId);
In above you will get only those resources with flow_type = 2
I ended up using the following statement:
Job::with(['resources' => function ($query){
$query->wherePivot('flow_type', '=', '1' );
}, 'resources.resourceTypes'])->where('id', $projectId)->firstOrFail();
$result = DB::table('job')
->join('job_resources', 'job.id', '=', 'job_resources.job_id')
->join('job_requests', 'job_resources.request_id', '=', 'job_requests.id')
->where('job_resources.flow_type', '=', CONDITION)
->get();
Your table data is not clear from your input, but this method (query builder) should work

query with Laravel Eloquent ORM

How can I make this query in Laravel, using Eloquent ORM?
select * from posts p order by ( select count(*) from likes where flag = 'c' and p.id = post_id ) Desc limit 3
I have this relationship in my models
Post.php
public function likes(){
return $this->hasMany('Like', 'post_id');
}
Like.php
public function post(){
return $this->belongsTo('Post', 'post_id');
}
Thanks! :)
You may try something like this:
$posts = Post::leftJoin('likes', function($join) {
$join->on('posts.id', '=', 'likes.post_id')->where('flag', '=', 'c');
})
->select('posts.*', 'likes.post_id', DB::raw('count(likes.post_id) as pCount'))
->groupBy('post_id')
->orderBy('pCount', 'desc')
->take(3)
->get();

Resources