I have a maintenance table with the following fields: id, car_id, type, and name.
How do I get list of entries from maintenance table where type = 'car wash' but only with model_id = 5?
model_id field are in the car table. Car table with the following fields: id, model_id, engine_size, and color.
How can I use Maintenance::where to get list of entries with matching model_id in a car table? There is car_id in a maintenance table which link with car table.
Do I need to do something like this: ?
return Maintenance::where('type', 'car_wash')->where(function($query) {
// get a list a maintenance where model_id = 5 in a car table
});
Assuming you've already defined cars() relation on your Maintenance model you could try something like that:
$model_id = 5;
$type = 'car_wash';
return Maintenance::whereHas('cars',function($query) use($model_id,$type) {
$query->where('model_id',$model_id)->where('type',$type);
})->get();
Update for further question (skip if $model_id = 0):
return Maintenance::whereHas('cars',function($query) use($model_id,$type) {
if($model_id!=0){
$query->where('model_id',$model_id);
}
$query->where('type',$type);
})->get();
I did not tested it but it should work, otherwise let me know
Related
I have 3 tables (products, product details, loan reports).
I want to display product categories in the loan report table. the product table has one-to-many relation with the product detail table and the product detail table has one-to-many relation with the loan report table.
Products
id
product_categories
Product Details
id
product_name
Loan Reports
id
date
amount
I've displayed it using this code,
$data = DB::table('loan_reports')
->join('product_details', 'loan_reports.product_details_id', '=', 'product_details.id')
->join('products', 'product_details.products_id', '=', 'products.id')
->get();
I want to do it with Eloquent orm but it's always get an error.
Help me please!
the column I want to display is roughly like this
| date | product_categories | product_name | amount |
The error that I get is the following:
Trying to get property 'product_name' of non-object
You might want to check out "has many through" relationship:
https://laravel.com/docs/5.8/eloquent-relationships#has-many-through
In ProductDetails model,create relationships.
public function product_info()
{
return $this->belongsTo('App\Models\Product','id','products_id');
}
public function loan_reports()
{
return $this->hasOne('App\Models\LoanReports','product_details_id','id');
}
Retrieve result using
$product_details = ProductDetails::get();
foreach($product_details as $product_details)
{
echo $product_details->product_categories;
if(isset($product_details->product_info))
{
echo $product_details->product_info->product_name;
}
if(isset($product_details->loan_reports))
{
echo $product_details->loan_reports->date;
echo $product_details->loan_reports->amount;
}
}
I have 3 tables: reports, fields and report_fields which is a pivot between the other 2. What i need to do is order report_field.field by the position column in the field table.
I tried ordering in the relation in the Models or when using with but I may be doing it wrong.
ex:
$query = Report::with([ 'reportFields.field' => function ($q) {
$q->orderBy('position', 'asc');
//$q->orderByRaw("fields.position DESC");
},
Can someone give a basic example of ordering a 2 level nested relationship?
Edit: I do not need to order by any column in the base table but the list of entries in the pivot table by an column in the second table.
Edit2:
To give an example how the output should be ordered:
Report
ReportField
Field.position = 1
ReportField
Field.position = 2
ReportField
Field.position = 3
You can add your needed ordering on the relation of the first table reports:
public function reportFields()
{
return $this->hasMany(ReportFields::class)
->select('report_fields.*')
->join('fields', 'report_fields.field_id', 'fields.id')
->orderBy('fields.position', 'asc');
}
I have a pivot table. The name is users_banks table. The table have field id, user_id, bank_id, status, account_name and account_number
Now, the pivot have 3 records
I display contain from pivot table using code like this :
$user_id = auth()->user()->id;
$user = $this->user_repository->find($user_id);
$account = array();
foreach($user->banks as $bank) {
$account[] = $bank;
}
dd($account);
The result display all record in the form of array. There exist value of field user_id, bank_id, status etc. But I don't find value of id
How can I find id from pivot table?
If the relationship is defined correctly you can use:
$bank->pivot->id
but make sure the user belongsToMany(Bank::class) and the bank belongsToMany(User::class) or else it wont work.
I'll explain my structure first so you can understand what I'm trying to get
1 - Car = name - model - age
2 - User = name - city - phone
3 - Reservation = from_date - to_date
4- reservation_user = user_id - reservation_id
5 - car_user = user_id - car_id
In the view.blade I tried to show the user's info in a table and below that the user request car's descriptions ( he wants to buy) and below that if he has a car he wants to rent (ONLY rent)
table user's info
table with all the cars he request ( both rent and buy)
table with car id and the dates the user want the car from-to
public function show($id)
{
$users = User::with('cars')->where( 'id',$id)->get();
return view('show')->withusers($users);
}
the way I saved the cars for sales
$id = $new_cars->id;
$user->cars()->attach($id);
for rent
$id = $new_car->id;
$R_id = $time->id;
$user->cars()->attach($id);
$user->reservations()->attach($R_id);
problem
the cars for rent is displaying in both tables because in the function I pulled all the cars.
Question
how can I get only the cars with reservation in one table(third table)? Without displaying them in the second table
First of all, you didn't design your car_user pivot table properly. You are storing the relationship for User and Car in that table but you are storing both types of relationship data using same properties, for sell and rent and there's no way to distinguish the difference as which one is for sell and which one is for rent. So, at first, you've to make a difference between both types of relationships using another field in that pivot table, so let's add another field in the table which will allow you to find out the relationship type, for example:
Table car_user:
user_id | car_id | type
------------------------
1 | 1 | buy
1 | 2 | rent
Here, the type will be used to identify the type of the relationship whether it's a rent or sell. So, when you attaching the relationship, add the type field (rent/buy) but before that, you've to make the relationship for them. So, you may use two separate relationship methods in User model, for example:
// For Rent
public function rentingCars()
{
return $this->belongsToMany(Car::class)
->wherePivot('type', 'rent')
->withPivot('type');
}
// For Buy
public function buyingCars()
{
return $this->belongsToMany(Car::class)
->wherePivot('type', 'buy')
->withPivot('type');
}
// For both types
public function buyingCars()
{
return $this->belongsToMany(Car::class)->withPivot('type');
}
Now, you can query for certain types of car using something like this:
public function show($id)
{
// Load all cars the user wants to buy
$users = User::with('buyingCars')->where( 'id', $id)->get();
// Notice "withUsers" not "withusers" (you've used "withusers")
// Or: view('show')->with('users', $users);
return view('show')->withUsers($users);
// More examples:
// Load all cars the user wants to rent
// $users = User::with('rentingCars')->where( 'id', $id)->get();
// Load all cars the user wants to buy or sell
// $users = User::with('cars')->where( 'id', $id)->get();
}
Now, when you attaching the cars to User model, you have to pass the value for the type field as well:
// For rent
$user->cars()->attach($car_id, ['type' => 'rent']);
// For buy
$user->cars()->attach($car_id, ['type' => 'buy']);
Also, when you do something like this:
$user = User::with('cars')->find(1);
You can check wheather a car is for rent or buy using something like this:
#foreach($user->cars as $car)
{{ $car->name }}
// Either buy or rent
{{ $car->pivot->type }}
#endforeach
I have 3 tables
type
type_id
person
person_id
category
category_id
table_name
table_id
person_id
In category I have connections of different tables/models with Type model, So if I have want to get type_id connected with person with person_id = 23 the query should look like this:
SELECT * FROM category WHERE table_name='person' AND table_id = 23
In my Person model I defined relationship with Type this way:
public function groups()
{
return $this->belongsToMany('Type', 'category',
'table_id', 'type_id')->wherePivot( 'table_name', '=', 'person' );
}
When I want to get those types and I use:
$person->groups()->get()
The query looks like this:
select `type`.*, `category`.`table_id` as `pivot_table_id`, `category`.`type_id` as `pivot_type_id` from `type` inner join `category` on `type`.`type_id` = `category`.`type_id` where `category`.`table_id` = '23' and `category`.`table_name` = 'person';
so it seems to be correct.
But I would like to use sync() for synchronizing types with persons and here's the problem.
When I use:
$person->groups()->sync('1' => ['table_name' => 'person']);
I see the query that gets all records from category to use for sync looks like this:
select `type_id` from `category` where `table_id` = '23';
so it doesn't use
`category`.`table_name` = 'person'
condition so synchronization won't work as expected.
Is there any simple way to solve it or should I synchronize it manually?
You should use Eloquents polymorphic relations (http://laravel.com/docs/4.2/eloquent#relationships)
class Category extends Eloquent {
public function categorizable()
{
return $this->morphTo();
}
}
class Person extends Eloquent {
public function categories()
{
return $this->morphMany('Category', 'categorizable');
}
}
Now we can retrieve catgories from person:
$person = Person::find(1);
foreach ($person->categories as $category)
{
//
}
and access person or other owner from category:
$category = Category::find(1);
$categorizable_model = $category->categorizable; //e.g. Person
I can confirm that it was a bug in Laravel 5 commit I used. I've upgraded for Laravel 5 final version and now query is generated as it should.