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
Related
I want to user orders data by specific month in a year.
Here is my order Table
id | user_id | price | quantity | total
Here is my order model
public function user() {
return $this->belongsTo(User::class);
}
Here is my user model
public function orders(){
return $this->hasMany(Order::class);
}
In a controller, by doing this I get all user orders
$user= User::with('orders')->get();
dd($user->orders);
Now, How can I get specific month user orders detail?
I want to show all user list with their order's total amount by month.
Try this to get users with their orders' total of September:
$users = User::withSum(['orders as september_total' => function ($query) {
$query->whereMonth('created_at', '9'); // September
}, 'total'])->get();
This will place a september_total attribute on your resulting models.
Take a look at these two queries:
$users = User::query()->with(['orders' => function($q){
$q->whereRaw('MONTH(orders.created_at) = 2');
}])->get();
// eager load all orders that have been created on month 2
$users = User::query()->whereHas('orders', function($q){
$q->whereRaw('MONTH(orders.created_at) = 2');
})->get();
// you'll get all users with orders on month 2 (no eager loading)
You can of course combine with (eager load) and whereHas (filter users) in order to "only get the users that have orders on month 2 AND eager load those orders".
Of course, feel free to use another column (e.g. ordered_at) or change the month if you need to.
I want to be able to make relationships between a captain and his referrals. They both belong to the same table. I have this in my model
public function captain() {
$this->belongsTo('User', 'referral_id') ;
}
public function captain() {
$this->hasMany('User', 'referral_id') ;
}
My users table has the following columns
id name referral_id referred_by
1 xyz 1223 null
2 Abc 4525 1223
How do I create the relationship better? And I want to know if I can and how I can use this to get the referral of a referral of the captain
I'd create a second table for your referrals - then you create a relationship between your captain ID in table 1 over in table 2 where all the referers can be stored. If you setup the relationship, you then simply call something like
$captains = App\Captain::all();
foreach ($captains as $captain) {
echo $captain->referrals->name;
}
ref
using simple eager loading... or ->with using other methods (or join etc)
I have two models: Report and User. This is what I have in my User model
public function userReport() {
return $this->hasMany('App\Report', 'user_id','id');
}
And this is in Report model
public function user() {
return $this->hasOne('App\User', 'id', 'user_id');
}
Controller
public function details( $item_id ){
$report = Item::find($item_id)->report;
return view('details', compact('report'));
}
In view
{!! $report->user->name !!}
In view I show all the users who are reported single Item .. which I query by $item_id.
The problem is that if same user is reported single item 1+ time I see this user 1+ time in the table on the page.
Is it possible to somehow grouped by user_id or count the user_id and show User1 ( 4 time reported ) ...? Where should I group them?
Update: users table
id | username | password
reports table
report_id | id | user_id | date
item table
id | user_id | category | date_added | image
Update2: Image of records in db. Here user with user_id=3 has reported item_id=14 total of 14 times. User with user_id=5 has reported same item_id=14 total of 3 times. So I should see on page user_id=3 ( 14 ) and user_id=3 ( 3 ). Instead I see 17 times user_id=3. Bellow are images
And on page
There should be several ways how to solve your problem
One way is (your controller should look like)
public function details( $item_id ){
$report = Item::find($item_id)->report->unique('user_id');
return view('details', compact('report'));
}
Second way should be to use #foreach in view and there check for unique values.
Third way should be to use foreach in controller and prepare unique data with calculated summarizes inside controller and then pass that prepared data to view.
Which soulution you want to use is just a matter of choice.
Hope it helps you
Just try this. Hope it helps
Report::where('item.id', $item_id)
->select('item.*','users.*',DB::raw('count(reports.report_id) as total'))
->join('item', 'item.id', '=', 'reports.id')
->join('users', 'users.id', '=', 'reports.user_id')
->groupBy('reports.report_id','reports.id')
->get();
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
I have a table which stores the user's interested topics along with the user id and topic id. The table will look like
Topic name topic id User-id
Sports 1 1
Education 2 3
Family 3 1
What i want to do is when a new user , say user-id '3' adds his interest as topic sports , then the first row should look like this
Topic name topic id User-id
Sports 1 1,3
When i try to update it overwrites the whole column like
Topic name topic id User-id
Sports 1 3
What is the right approach to do this ?
The right approach is to use Many-To-Many relationship:
Tables:
users (id, ....);
topics (id, ....);
topic_user (topic_id, user_id);
PHP:
class User extends Model {
public function topics() {
return $this->belongsToMany('App\Topic');
}
}
and :
class Topic extends Model {
public function users() {
return $this->belongsToMany('App\User');
}
}
For more details please refer to https://laravel.com/docs/5.2/eloquent-relationships.
I hope this will help.