Laravel Check column using relationship column - php

I need to query and check if the relationship column is the same in my main table column.
example codes:
not working
User::with('product', => function($q) {
$q->whereRaw('users.company_id',' product.company_id');
})->get();
not working
User::with('product', => function($q) {
$q->whereRaw('users.company_id = product.company_id');
})->get();
not working
User::with('product')->whereColumn('users.company_id', 'product.company_id')->get();
but it's not working..
any idea how to do it?
My Models
User Model
public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}
Product Model
public function users()
{
return $this->hasMany(User::class, 'product_id');
}

Please try again:
User->with(['product' => function ($query) {
$query->join('users', 'users.company_id', '=', 'product.company_id');
}])->get();

Try to use DB:raw() then show the table info? like this

Related

Laravel Eloquent Model with relationship

I have implemented eloquent relationship in my code but Laravel unable to read the function that I created to map the eloquent relationship in the model.
User Model
public function products(){
return $this->hasMany(Product::class,'userid');
}
Product Model
public function users(){
return $this->belongsTo(User::class);
}
Product Controller
$products = Product::with('Users')->Users()->where('users.isActive',1)->get();
return view('product',compact('products'));
I keep getting error from the product controller, I also attached the error that I current encountered as below.
How can I get all the product and user data with the where condition such as "Users.isActive = 1".
Thanks.
You can use whereHas to filter from a relationship.
$products = Product::with('users')
->whereHas('users', function ($query) {
$query->where('isActive', 1);
})
->get();
Also it is generally a good idea to use singular noun for belongsTo relationship because it returns an object, not a collection.
public function user() {
return $this->belongsTo(User::class);
}
$products = Product::with('user')
->whereHas('user', function ($query) {
$query->where('isActive', 1);
})
->get();
EDIT
If you want to retrieve users with products you should query with User model.
$users = User::with('products')
->where('isActive', 1)
->get();
Then you can retrieve both users and products by
foreach($users as $user) {
$user->products;
// or
foreach($users->products as $product) {
$product;
}
}
You can use whereHas() method for this purpose. Here is the doc
$products = Product::with('users')->whereHas('users', function (Illuminate\Database\Eloquent\Builder $query) {
$query->where('isActive', 1);
})->get();
$users = $products->pluck('users');
return view('product',compact('products'));
You have a typo after the with, is users instead of Users and you're redundant about the Query Builder, remove the ->Users():
Before:
$products = Product::with('Users')->Users()->where('users.isActive',1)->get();
return view('product',compact('products'));
After:
$products = Product::with('users')->where('users.isActive',1)->get();
return view('product',compact('products'));
Fix that and all should work.

Laravel how to get users based on model exists or not

In my laravel-application I want to display a list of all users/candidates. So far I have this, which basically works fine:
public function candidates()
{
$users = User::whereHas(
'roles',
function ($q) {
$q->where('slug', 'candidates');
}
)->get();
return response(['success' => true, "users" => $users], 200);
}
Now, I actually want to display users/candidates who have taken an education. I have a Model called UserEducation but I don't really know to include it to get the data out I want.
can someone help me out?
EDIT
In my User model, I have this relation:
public function educations()
{
return $this->hasMany('App\Models\UserEducation');
}
you can use has:
$users = User::has('UserEducation')->whereHas(
'roles',
function ($q) {
$q->where('slug', 'candidates');
}
)->get();
You can try create relationship with User and UserEducation models and then get data.
https://laravel.com/docs/7.x/eloquent-relationships

accessing relationship from model laravel

i have a two tables where user table has a one to one relationship with role table
this is my user model
public function role(){
return $this->belongsTo(Role::class);
}
this is my role model
public function user(){
return $this->hasOne(User::class);
}
this my table structure for role
this my table structure for user
how can i access in my user model the role which is equal to employee
i tried
User::with('role')->where('role_name','employee')->get();
but it has an error
role_name column not found
This will give you only the users which has an employee role .
User::whereHas('role', function ($query) {
$query->where('role_name', 'employee');
})->get();
And this will give you all the users with their employee roles if any exist
User::with(['role' => function ($query) {
$query->where('role_name', 'employee');
}])->get();
Try this:
User::whereHas('role', function ($query) {
$query->where('role_name', 'employee');
})->get();
Details at: https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-existence
Try this:
User::with(['role' => function ($query) {
$query->where('role_name', 'employee');
}])->get();

Laravel Eloquent deep nested query

I'm still learning Laravel and I can't find the solution for this problem.
I need to get invoices(with expenses) that are related to specific Partner Type.
I tried this:
$p = Project::with(['invoices.partner.partnerType' => function($query){
$query->where('partnerTypeName', 'Lieferant');
}, 'expenses'
])->where('id', $id)
->first();
I want to select invoices for Lieferant, but I get all invoices for one project.
Project Model:
public function invoices()
{
return $this->hasMany('App\Invoice');
}
Invoice Model
public function expenses()
{
return $this->hasMany('App\Expense');
}
public function partner()
{
return $this->belongsTo('App\Partner');
}
Partner Model
public function partnerType()
{
return $this->belongsTo('App\PartnerType');
}
Edit: PartnerType Model
public function partners()
{
return $this->hasMany('App\Partner');
}
Edit 2: Database
Partner(partnerID, name, partnerTypeId)
PartnerType(partnerTypeId, partnerTypeName)
Project(projectID, name)
Invoice(invoiceID, name, projectID, partnerID)
Expenses(expenseID, invoiceID)
If your models look like that.
Should be like :
$p = Project::with(['invoices' => function($query){
$query->where('partnerTypeName', 'Lieferant')
->with(['expenses','partner' => function($q){
$q->with('partnerType');
}]);
}])->where('id', $id)
->first();
return dd($p);
The solution to your problem is to update your query like this:
$p = Project::with(['invoices' => function($query){
$query->with('expenses')->whereHas('partner.partnerType', function($q){
$q->where('partnerTypeName', 'Lieferant');
});
}])
->where('id', $id)
->first();
But a cleaner solution would be using a scope for your problem.
In your Invoice model.
// Invoice.php
public function scopeByPartnerType($query, $partnerType)
{
$query->whereHas('partner.partnerType', function($q) use ($partnerType) {
$q->where('partnerTypeName', $partnerType);
});
}
And then in your Project model, add another relation that will just get Invoices with a particular partner type.
// Project.php
public function lieferantInvoices()
{
return $this->hasMany('App\Invoices')->byPartnerType('Lieferant');
}
Now you can do just this:
$project->find($id)->load('lieferantInvoices');

How to query multiple relationships in laravel eloquent

I'm kinda stuck here while querying multiple relationships in laravel eloquent I had the raw query like
SELECT * FROM tblSchedules,tblUserHomeCourts,tblHomeCourts
where tblHomeCourts.userId=6
and tblHomeCourts.homeCourtId=5
and (tblSchedules.timeFrom <= 1495617580
and tblSchedules.timeTo >= 1495617580)
and tblUserHomeCourts.userHomeCourtStatus=1
and tblSchedules.scheduleStatus=0
now I need to query this raw query into laravel eloquent. I've tried to to do so like this
$getSchedule= Schedule::with(['userSchedule' => function($query) use ($userId,$homeCourtId,$timeFrom, $timeTo) {
$query->where(['userId'=> $userId,'homeCourtId'=>$homeCourtId,'userHomeCourtStatus' => Constant::STATUS_1]);
}]) ->where('timeFrom','<=',$timeFrom)
->where('timeTo','>=',$timeTo)
->where(['scheduleStatus'=>Constant::STATUS_0])
->get();
but I'm not getting the result instead of this I'm getting blank message array where I'm supposed to get the records.
Question:
what I have done wrong?
suggest me the correct way of query this query.
Schedule Model
public function friendsFeed(){
return $this->hasOne(UserHomeCourt::class,'userHomeCourtId','userHomeCourtId')->with('user')->with('homeCourt');
}
public function userSchedule(){
return $this->hasOne(UserHomeCourt::class,'userHomeCourtId','userHomeCourtId')->with('homeCourt');
}
UserHomeCourt Model
public function homeCourt(){
return $this->belongsTo(HomeCourt::class,'homeCourtId','homeCourtId');
}
public function user(){
return $this->belongsTo(User::class,'userId','userId');
}
}
HomeCourt Model
public function friendsFeed()
{
return $this->hasOne(UserHomeCourt::class, 'homeCourtId', 'homeCourtId');
}
public function userSchedule()
{
return $this->hasOne(UserHomeCourt::class, 'homeCourtId', 'homeCourtId');
}
Response I have got from SQL Query
The time check from your sql to eloquent was wrong and when you pass multiple conditions to where, you need to set the conditions as an array.
$getSchedule= Schedule::with(['userSchedule' => function($query) use ($userId, $homeCourtId) {
$query->whereHas('homeCourt', function ($query) use ($userId, $homeCourtId) {
$query->where('userId', $userId)
->where('homeCourtId', $homeCourtId);
})->where('userHomeCourtStatus', 1);
}])
->where('timeFrom', '<=', $timeFrom)
->where('timeTo', '>=', $timeTo)
->where('scheduleStatus', 0)
->get();
try to use whereHas function:
Schedule::whereHas('userSchedule', function ($query)
{
$query->where('userId', $userId)
->where('homeCourtId', $homeCourtId)
->where('userHomeCourtStatus', Constant::STATUS_1);
})
->where('timeFrom', '<=', $timeFrom)
->where('timeTo', '>=', $timeTo)
->where('scheduleStatus', Constant::STATUS_0)
->get();

Categories