I have two models:
Order
Customer
I have customer_id in orders table. Customer details (name, phone, email etc) in customerstable. But I am writing query for orders table.
Now, I want to search with Customer Name on Orders but in Orders table I just have customer_id.
How will I link up with customers table so that I can search with Customer Name. I want to do that with Eloquent.
How is this possible?
There are multiple ways of doing relationship filtering with Eloquent.
You can achieve it with whereHas or using an advanced join / left join query.
I suggest you do a research about Eloquent filtering on Laravel documentation, everything you need for your task should be there.
https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
https://laravel.com/docs/8.x/queries#advanced-join-clauses
In models define relationships
Customer model
public function orders()
{
return $this->hasMany(Orders::class);
}
Order model
public function customer()
{
return $this->belongsTo(ustomer::class, 'foreign Key', 'id');
}
Then you can call relationships and search what you want
Customer::whereHas('orders')
First you need to create relationship in the orders model, you can use either belongsTo or hasOne relationship.
belongsTo relationship will be like as below
public function customer()
{
return $this->belongsTo(ustomer::class, 'foreign Key', 'id');
}
and the hasOne relationship will be like as below
public function customer()
{
return $this->hasOne(Customer::class, 'foreign_key', 'local_key');
}
The search function will be like as below
public function OrderSearch(Request $request){
try {
/**
* Fetching data with orders relationship
*/
$orders = OrdersModel::with(['customer'])
if(!empty($request->search)){
/**
* Searching the name key inside
* the customer relationship
*/
$orders->where(fn($query)=>
$query->whereHas('customer',fn($query2) =>
$query2->where('name','LIKE','%'.$request->search.'%'));
);
}
/**
* Returning the response
*/
return $orders->get();
} catch (\Throwable $th) {
throw $th;
}
}
Kindly refer the laravel eloquent-relationships documentation : eloquent-relationships
Related
I have many-to-many relationship users|pivot|task
I need to order records by pivot table column(role) and by user table column(name). Ordering by pivot works, but order by users doesnt. Please give any advice how to fix this
Job model
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class,'user_job')
->using(UserJob::class)
->withPivot('role')
->withTimestamps();
}
User Model
public function jobs(): BelongsToMany
{
return $this->belongsToMany(Job::class,'user_job')
->using(UserJob::class)
->withPivot('role')
->withTimestamps();
}
Repository
return User::find($dto->getUserId())
->jobs()
->where($dto->getFilters())
->with('users')
->orderBy($dto->getSortBy(),$dto->getSortType()) // need to order by users.name
->paginate($dto->getPerPage());
I have a model called unit that has this relationship
/**
* Get the users associated with the unit
*/
public function users()
{
return $this->hasMany('App\Models\User\UserData');
}
In the UserData model there is a column called user_id which I am trying to put in my condition in my query. I am trying to do a query like this
Unit::where('user_id', Auth::id())->first()
but there is no user_id column in the Unit table, only though the users relationship
Ended up doing this
Unit::whereHas('users', function($q) {
$q->where('user_id', Auth::id());
})->first();
i've a question about Laravel Relationships.
I've a raw union query and i want to translate into a eloquent relationship.
First of all... i have 4 tables involved:
roles
id|name
permissions
id|name|code|description
permission_role
role_id|permission_id
users
id|...........|role_id
permission_user
user_id|permission_id
Inside my User model, i've this method:
/**
* #TODO: Transform this into a eloquent relationship
*
* #return Collection
*/
public function permissions()
{
$query = sprintf('
(
SELECT permissions.*
FROM permissions
INNER JOIN permission_role ON permission_role.permission_id = permissions.id
WHERE permission_role.role_id = %s
) UNION
(
SELECT permissions.*
FROM permissions
INNER JOIN permission_user ON permission_user.permission_id = permissions.id
WHERE permission_user.user_id = %s
)', $this->role_id, $this->id);
return Permission::hydrate(DB::select($query));
}
The point is, i want to fetch all permissions by the role that the user is associated, and the separated permissions associated to the user.
Can i transform this in some eloquent relationship like hasMany, belongsToMany, etc... ?
The "merge" function in Laravel collection might be able to help you.
The big differnt is that I close off the query with ->get() in advance, and I use merge() instead of union()
// In Controller
public function GetUsersWithPermission()
{
$permissionByRole = User::with('permission_role.permission')->get();
$permissionByUser = User::with('permission_user.permission')->get();
$result = $permissionByRole->merge($permissionByUser);
}
// User Model : get PermissionRole By User
public function permission_role() {
return $this->hasOne('App/Model/permission_role', 'role_id', 'role_id'); }
public function permission_user() {
return $this->hasOne('App/Model/permission_user', 'user_id', 'id'); }
// permission_role Model : get Permissions By Role
public function permission(){
return $this->hasMany('App/Model/Permissions', 'id', 'permission_id'); }
// permission_user Model : get Permissions By User
public function permission(){
return $this->hasMany('App/Model/Permissions', 'id', 'permission_id'); }
Note: I don't have your data so I can't proof it work, but it least it work on my data so should worth your try. and it return all data like: all user details, and permissions so you can use select() function to get Specific Columns.
How to join the three table in Laravel Eloquent model. My table structure is like. It is easy with raw(mysql with left join) query to get the desired result, but it is possible to get via Eloquent.
Customer table
id
title
name
Order table(has customer id)
id
customer_id
Hour table (has order id)
id
order_id
From Hour model I want to get the Customer Details and Order Details. Now I am able to get the Order details like below.
public function order()
{
return $this->belongsTo('App\Models\Order', 'order_id', 'id');
}
How to get the Customer Details?
I tried like below, but not get success
1.return $this->hasManyThrough('App\Models\Customer','App\Models\Order','customer_id','id');
2. return $this->hasManyThrough('App\Models\Customer','App\Models\Order','customer_id','order_id');
Edit 1:
class HourLogging extends Model
{
public function order()
{
return $this->belongsTo('App\Models\Order', 'order_id', 'id');
}
$timeoverview = HourLogging::select('hour_logging.*')->whereRaw("hour_logging.date BETWEEN '".$start_date."' AND '".$end_date."'")->orderBy('date','asc');
$timeoverview->with('order.customer');
return $timeoverview->get();
}
class Order extends Model {
public function customer() {
return $this->belongsTo('App\Models\Customer');
}
}
hasManyThrough works the opposite way to what you're trying to achieve. It would let you get Hour models from your Customer model easily.
In order to get what you need you need to define the relations that go the other way - from Hour to Order to Customer. Add the following relations to your models:
class Hour extends Model {
public function order() {
return $this->belongsTo('App\Models\Order');
}
}
class Order extends Model {
public function customer() {
return $this->belongsTo('App\Models\Customer');
}
}
With those relations in place you should be able to access Order data with $hour->order and Customer data with $hour->order->customer.
One thing to remember: Eloquent offers possibility to eagerly load related data to avoid additional queries. It makes sense to do it when you fetch multiple Hour records at once. You an load all Hour records with related Order and Customer data with the following:
$hours = Hour::with('order.customer')->get();
I have two models:
class Order extends Eloquent
{
public function User()
{
return $this->belongsTo('User');
}
public function Product()
{
return $this->belongsToMany('Product');
}
}
and the second one is:
class Product extends Eloquent
{
public function Order()
{
return $this->belongsToMany('Order');
}
}
My question is how can i access a value of second table column using pivot table:
product table:
id
title
image
order table:
id
status
pivot table(order_product):
id
product_id
order_id
I need to access title column of products from orders. for example if a user orders many products in one order I can fetch all product title and show theme.
I don't like use join , instead I like to use Laravel functionality itself.
I found the answer:
$orders = Order::orderBy('created_at', 'DESC')->paginate($page_number);
foreach($orders as $item){
foreach($item->product as $item){
{{$item->title}}<br>
}
}
I can access products from order.