convert query from mysql to php laravel? - mysql

My query is the following:
select employe.id, employe.nam, users.name, users.name_user
from employe
left join users
on users.name = employe.id
it is a query to two tables: employe, users.
How can I pass it to my controller? Am I new to laravel..

I assume the user to employee is a One to One relation.
Did you setup the relation in both models?
If so you can do the following in your controller:
$employees = Employee::with('user')->all();
This will load all employees and the related user.
Question is the users.name a foreign key on the employee.id?
Thats a bit strange, i recommend using id's on both models (autoIncrement).

Laravel use a MVC pattern, a good practice is use a Model for your employe table
I recomend you to use an Eloquen Model, so, your query will look like this:
Employe::select('employe.id', 'employe.nam', 'users.name', 'users.name_user')
->leftJoin('users', 'users.name', 'employes.id')
->get();

You can easily maintain this kind of query with Eloquent relationships.
Add this method on your employee model
public function user(){
return $this->hasOne('App\User','name','id');
}
Add this method on your user model
public function Employee(){
return $this->belongsTo('App\Employee','id','name');
}
Add line on your controller
$employees = Employee::with('user')->all();

Related

How to return the data of another model instance model by using joins in laravel?

I want to return the data of Charge instance instead of User , for that i am trying to use joins ,can you please help me to acheive this thing
$id=Charge::whereNotNull('created_by')->get('created_by')->toArray();
foreach($id as $name){
$id[] = $name['created_by'];
}
return $v=User::whereIn('id',$id)->where('username',$request->data)->get();
}
for this i am trying to use left join , relationship available between created_by and id (I am trying to convert above queries into single query)
$v=Charge::whereNotNull('created_by')->leftJoin('User',function($join){
$join->on('Charge.created_by','=','User.id');
})->get();

Laravel (Lumen) Eloquent querying with WHERE on a relation (Multi-level)

I have the following DB tables:
Purchase
-id
-workplace_id
Workplace
-id
-client_id
(and obviously some more fields, but for the example these are all the needed ones).
I would like to make a query like this:
SELECT * FROM
purchase
INNER JOIN workplace ON (purchase.workplace_id = workplace.id)
WHERE
(workplace.client_id = 1)
I'm trying to make this work with the Eloquent models, but I can't figure out how to filter on a joined table.
I tried:
$purchases = Purchase::query()
-> workplace()
-> where('client_id', '=', Auth::user() -> client_id)
-> get();
But apparently workplace() is undefined for some reason.
My Purchase.php model file looks like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Purchase extends Model
{
public function workplace(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Workplace::class);
}
}
Any pointers on how to make this simple select work?
Thanks!
====EDIT=====
I found a possible solution:
$purchases = Purchase::with('workplace')
-> whereHas('workplace', function($q) {
return $q -> where('client_id', '=', Auth::user() -> client_id);
})
-> get();
But this generates an SQL that seems more complicated and is probably also slower:
select * from `purchases` where exists (select * from `workplaces` where `purchases`.`workplace_id` =
`workplaces`.`id` and `client_id` = ? and `workplaces`.`deleted_at` is null)
So I'm still looking for better alternatives
If you want to do a join, you need to build it with the join method, you can't use a relationship. See here for the docs:
https://laravel.com/docs/9.x/queries#joins
So you should be able to do something like this:
$purchases = Purchase::query()
->join('workplace', 'purchase.workplace_id', '=', 'workplace.id')
->where('workplace.client_id', '=', Auth::user()->client_id)
->get();
The generated SQL that you show in your edit is a sub-query, and you may still want to consider that. Sure, sub-queries are often slower than joins, but unless you're dealing with a massive dataset the performance difference might be negligible, and it allows you to use native Eloquent relationships.
See here for a discussion on this: https://stackoverflow.com/a/2577188/660694

Using foreign key to get all product from another table?

I have two table Order_table and Invoice_table ,i have order_id of Order_table which is foreign key of Invoice_table.
How to write the query in this situation in Laravel.
You should rather try to use eloquent relationship for this sort of problem. You can see here for the reference https://laravel.com/docs/5.6/eloquent-relationships#one-to-one
As you said you should only include _"order_id"_ column in your invoices databse table.
In your Order.php model, write this code:
public function invoice()
{
return $this->hasOne('App\Invoice');
}
In your Invoice.php model, write this code:
public function order()
{
return $this->belongsTo('App\Order');
}
and from the Controller you can use the eloquent query to get data. For example, you can get random 3 data using this code:
$results = Invoice::limit(3)->get();
echo $results->order;
If we suppose that the name of the models are Invoice and Order, you can use this code :
$invoice = Invoice::find($invoice_id);
$orders = $invoice->orders();

Eloquent Query, possible Join

I have three models: driver, designation and dpsObject, with the following replationships:
driver->hasMany(dpsObject)
driver->belongsTo(Designation)
designation->hasMany(Driver)
dpsObject->belongsTo(Driver)
I'm trying to write a query to return a list of dpsObject records that correspond to the values of three user inputs, which are: a date range(From and To) holding the values of an EntryDate field in the dpsObject and a Designation input, holding the value of a Designation_name field in the Designation object.
Currently this is my Query:
$dps = dpsObject::where([['entryDate', '>=', $from],
['entryDate', '<=', $to]]);
$from and $to hold the request values gotten from the form user's submit.
I need to complete the query to capture the Designation name of a driver that that has dpsObject records. The challenge is that the designation_name field does not exist on the dpsObject model but only on the driver and designation models. This is how I want to maintain the database model. I think I need to be using a join or something similar, but I'm not sure how to go about it.
What is the best way to write such a query?
Kind regards
You can use nested whereHas():
$dpsObjects = dpsObject::whereBetween('entryDate', [$from, $to])
->whereHas('driver', function ($q) use($designationName) {
$q->whereHas('designation', function ($q) use($designationName) {
$q->where('designation_name', $designationName);
});
})
->get();
Here, designation and driver are belongsTo() relationships.

Error in setting up laravel Eloquent relationship

I am trying to set up a relationship in Laravel using the eloquent relationship model, it looks like the one below
users
id
email
projects
id
name
user_projects
user_id
project_id
role
I want to be able to query the projects that the user is a part of irrespective of the role that he has. To do this, I used the following in my user model.
class User extends Model {
public function allProjects() {
return $this->belongsToMany('App\ProjectRoles', 'user_projects', 'user_id', 'project_id');
}
}
But because of this I get an error in my code
Syntax error or access violation: 1066 Not unique table/alias: 'user_projects' (SQL: select `user_projects`.*, `user_projects`.`user_id` as `pivot_user_id`, `user_projects`.`project_id` as `pivot_project_id` from `user_projects` inner join `user_projects` on `user_projects`.`id` = `user_projects`.`project_id` where `user_projects`.`user_id` = 2)
I am not sure how to create the join query in the relationships in order to do it. Any help would be appreciated. I went through the eloquent docs but wasn't able to get the result even though the examples there do exactly what I want.
Your belongsToMany relationship is related to the wrong Model. Generally you don't have a model for your pivot table, but even if you do, your belongsToMany relationship doesn't use it. Your User model should be related to your Project model.
You should use this:
class User extends Model {
public function allProjects() {
return $this->belongsToMany('App\Project', 'user_projects', 'user_id', 'project_id');
}
}