I have a customers table. These customers have a custumer_request table, and a customer can have more than one claim record. And there's a table of floors. The multiples table has a customer_request_floors table that is associated with the customer claims table. They are all related to each other. I want to filter customers who have demand according to the selected multiples when filtering customers.
In the search I use below, I want to filter it according to the latest requests of customers. When I filter as follows, it brings me linked records of that user's other requests. For example, let the customer have 2 requests. Let these be two different floor records. I'd like to search between multiples of the last request. When I filter as follows, it brings me the registered floor_id in 2 requests. I'm shooting your last request using a model. Can you help with filtering?
What I really want to look for is to filter the records with floor_id that I send in the pivot Table, which depends on the final demand from the customers.
Customer Model:
public function lastRequest()
{
return $this->hasOne(CustomerRequest::class)->latest();
}
Search Model:
$this->customers = $this->customers->whereHas('lastRequest', function ($customer_request){
$customer_request->whereHas('floors', function($floors) {
$floors->whereIn('floor_id', $this->params['floor_ids']);
});
});
CustomerRequest Model
public function floors()
{
return $this->belongsToMany(Floor::class, 'customer_request_floors');
}
customer_request_floors Pivot Table
protected $fillable = [
'customer_request_id', 'floor_id'
];
Related
I have 3 tables
User, Orders, Extra Orders
and I have used the hasMany method to get the data from tables. When data is inserted in the Extra Orders table having the user id and order id. but when two or three order are of same user id then it should club or combine all the extra orders in same card one by one. like https://prnt.sc/panfhi
but in my case, every row is having a different card. like https://prnt.sc/panga8 and my data is extracting as follows https://prnt.sc/panh0n
kindly advice the solution.
I have tried different methods of foreach loops but it's not working
getting the data from tables.
class GeneralController extends Controller {
public function orderReceived() {
$extra_orders = ExtraOrders::with(['user','orders'])->get();
dd($extra_orders->toArray());`enter code here`
}
}
check your relation function order
Order need to be Hasmany Relationship
I want to append the count of data from a table in my database but I am having a problem with the relationship.
I have 3 Models
Voucher model:
vouchers table
VoucherSerial Model:
voucher_serials table
Each voucher will have many serials
UserVoucher Model:
user_vouchers table
When the user redeemed the voucher it will be stored in user_vouchers table. I also had defined the relationship for all the Models
In Voucher.php I want to append the count of the voucher redeemed by the user.
public function getVoucherRedeemedAttribute()
{
//query to append the voucher redeemed count for each voucher
}
I've tried so many solution but mostly I got errors. My biggest problem is because to count the voucher redeemed for each voucher based on user_vouches table but each voucher has many serial_id which i want to count as the same voucher
I know my explanation regarding the question is bad but I need some help regarding this. Hope someone can help me.
Thank you so much in advance
You can add the number of related objects to the result with the withCount method:
If you want to count the number of results from a relationship without
actually loading them you may use the withCount method, which will
place a {relation}_count column on your resulting models. For example:
$posts = App\Post::withCount('comments')->get();
foreach ($posts as $post) {
echo $post->comments_count;
}
Source: https://laravel.com/docs/5.8/eloquent-relationships#counting-related-models
If I understand your problem correctly, you want to get the count one level deeper (number of vouchers instead of number of voucher serials). You might be able to use a hasManyThrough relationship:
The "has-many-through" relationship provides a convenient shortcut for accessing distant relations via an intermediate relation. For example, a Country model might have many Post models through an intermediate User model. In this example, you could easily gather all blog posts for a given country.
Source: https://laravel.com/docs/5.8/eloquent-relationships#has-many-through
Combined it will look something like this:
class User {
//...
public function vouchers()
{
return $this->hasManyThrough(App\Voucher::class, App\VoucherSerial::class);
}
}
// Controller
$user->withCount('vouchers');
I've never actually used withCount and hasManyThrough together but it should work ;)
I'm trying to build a store and everything is going great. But I'm running into an issue that I'm having trouble wrapping my head around to find the best option.
I have an Item Model:
class Item extends \Eloquent implements \Cviebrock\EloquentSluggable\SluggableInterface
{
protected $table = 'store_items';
public function options()
{
return $this->belongsToMany('\Dcn\Store\Option', 'store_items_options', 'items_id', 'options_id');
}
}
And an options model:
class Option extends \Eloquent implements \Cviebrock\EloquentSluggable\SluggableInterface
{
protected $table = 'store_options';
public function values()
{
return $this->belongsToMany('\Dcn\Store\OptionValues', 'store_option_values', 'options_id', 'op-values_id');
}
}
And an OptionValues Model:
class OptionValues extends \Eloquent
{
protected $table = 'store_op-values';
public function options()
{
return $this->belongsToMany('\Dcn\Store\Option', 'store_option_values', 'op-values_id', 'options_id');
}
}
And Finally an Invoice Model:
class Invoice extends \Eloquent
{
protected $table = 'store_invoices';
public function items()
{
return $this->belongsToMany('\Dcn\Store\Item', 'store_invoices_items', 'invoice_id', 'item_id');
}
}
When a user checkout I currently create an invoice and attach the items, but I need to be able to store the options (color, size, etc) for each item in the invoice.
I'm just not sure what the best way to store the values for the Items's options in the invoice because a user could have multiple items that are just different colors. Any input would be greatly appreciated.
One possible solution involves the following models/tables/relations:
Invoice
One To Many relation with InvoiceItems.
Invoice->hasMany('InvoiceItem')
InvoiceItem
This model contains the line items for each invoice, with invoice_id (foreign key) linking the InvoiceItem to Invoice, and item_id linking the InvoiceItem to an Item from your inventory. (Other order details would be stored here as well, such as quantity of the item, etc.)
InvoiceItem->belongsTo('Invoice')
InvoiceItem->belongsTo('Item')
Then, to store the options chosen for each InvoiceItem and their values, there's a One To Many relation with InvoiceItemOption.
InvoiceItem->hasMany('InvoiceItemOption')
InvoiceItemOption
For each InvoiceItem (linked by invoice_item_id), this model stores 0, 1, or more options (linked from the Option model by option_id) and that option's value (linked from the Value model by value_id).
InvoiceItemOption->belongsTo('InvoiceItem')
InvoiceItemOption->belongsTo('Option')
InvoiceItemOption->belongsTo('Value')
Item
This contains your list of items, i.e. your inventory. It has a One to Many relation with InvoiceItem (i.e. each Item can appear on many InvoiceItems, and each InvoiceItem has one Item). Each item also has 0, 1, or more Options available to it, so it is linked through a Many To Many relation with Option.
Item->hasMany('InvoiceItem')
Item->belongsToMany('Option')
item_option
This is a pivot table, linking each Item to its available Options (with item_id and option_id)
Option
All the available options for all Items. Each option has 1 or more possible Values, and is linked through a Many To Many relation with Value
Option->belongsToMany('Item')
Option->belongsToMany('Value')
option_value
This is a pivot table, linking each Option to its available Values (with option_id and value_id).
Value
All the available values for all Options.
Value->belongsToMany('Option')
For each relation, I've defined the inverse relation as well, which would give you maximum flexibility. Depending on your needs, though, some of those inverse relations might be unnecessary.
There are two other alternatives, neither of which I think are good ones:
You could link Invoices and Items via a Many To Many relation (as you've done), and store your invoice line item information in the intermediate invoice_item pivot table. To do this, though, you would need to create a custom pivot model (rather than a simple pivot table), since that model would need to have a hasMany('InvoiceItemOption') relation to store the selected options and values. This would limit your flexibility somewhat in how you interact with the InvoiceItem model, and there's nothing really to be gained by this approach.
(But, if your interested in a good example of how to set up such a custom pivot model, see https://github.com/laravel/framework/issues/2093#issuecomment-39154456.)
A third and even less optimal option would be to link Invoices and Items via a Many To Many relation, and store the options and values in a serialized form in the intermediary invoice_item pivot table, along with any other order details like quantity. To do this, you would need to specify the extra fields when you define the Invoice relation:
$this->belongsToMany('Items')->withPivot('quantity', 'options_serialized')->withTimestamps();
This method is very inflexible, though—running a query for orders containing extra-large green shirts, for example, would be a pain.
Struggling to update my code with laravel relationships.
I have two tables. Customer and Reservations with Customer having a hasMany relationship with Reservation and Reservation having a belongs to relationship with Customer.
The reservation table also has a many to many relationship with a product table via a link table.
I obtain the customer record ok and I now need to create a reservation for the customer.
I'm assuming the process is:
create the reservation object, attach the reservation to the customer and then link to the product. (the reservation table has a few relationships but I'll get this working for now)
If I try this code I get an error Field 'customer_id' doesn't have a default value - the database table allows null and there are no validation rules set so assume this is to do with the relationship I've set up.
`$reservation = new Reservation;
$reservation->play_date=$play_date->format('Y-m-d');
$reservation->booked_date=$booked_date->format('Y-m-d');
$reservation->am_tee=$am_time->format('H:i:s');
$reservation->pm_tee=$pm_time->format('H:i:s');
$reservation->save();
$customer->reservation()->associate($reservation);`
The error occurs with $reservation->save();
I then need to use the created $reservation to create entries in the product link table so need to be able to access the newly created reservation and it's relationship with products.
I can create the entry using $customer->reservation()->save($reservation); but then I don't seem to have a $reservation object to work with (or do I?)
I'm very confused by the relationships so grateful for all help to understand how to get this to work
Thanks
here's my relationships in the models:
Customer Class:
public function reservation() {
return $this->hasMany('Reservation');
}
Reservation Class:
public function customer() {
return $this->belongsTo('Customer');
}
The only method that appears to work is $customer->reservation()->save($reservation); - so I assume this is the correct method and will have to rework my code. associate()
update: recreated my table in mysql - I can now save the original reservation record as expected and then associate to the customer record using:
$reservation->customer()->associate($customer)
This is taking a while for it to sink in with me!
PART 1
since Customer hasMany Reservations, you need the customer id before you can add a reservation.
on your code,
you need to get the customer first that owns the reservation
$customer = Customer::find($id);
now,
$reservation = new Reservation;
$reservation->customer_id = $customer->id;
$reservation->play_date=$play_date->format('Y-m-d');
$reservation->booked_date=$booked_date->format('Y-m-d');
$reservation->am_tee=$am_time->format('H:i:s');
$reservation->pm_tee=$pm_time->format('H:i:s');
$reservation->save();
then, the $reservation->save(); should succeed now.
PART 2
on your question:
"I can create the entry using $customer->reservation()->save($reservation); but then I don't seem to have a $reservation object to work with (or do I?)"
you can get all reservations of a customer by using
$reservations = $customer->reservation->get();
//where customer is the one you had on Customer::find($id);
you can then loop on the reservations one by one. (although i think you might want the reservation ids, so the first approach above is better)
I have three tables: users, items and user_items. A user has many items and a item belongs to many users.
The tables:
Users
id
username
password
Items
id
name
equipable
User_items
id
user_id
item_id
equipped
The models:
class User extends Eloquent {
public function items()
{
return $this->belongsToMany('Item', 'user_items')
->withPivot('equipped');
}
}
class Item extends Eloquent {
public function users()
{
return $this->belongsToMany('User', 'user_items');
}
}
In the pivot (user_items) table I've a very important column named "equipped".
I've a form where users can equip, unequip and throw items. This form has a hidden field with the pivot (user_items) table row id. So, when a user tries to equip an item, the system checks if the item is equipable.
So, I want a object with the pivot data and the item data, based on item_id from the pivot table, I can send to the handler (where all logic is handled).
So what I've to do is to first access the pivot table and then access the item table.
Something like this (does not work):
$item = User::find(1)->items->pivot->find(1);
Is this possible to do?
You first have to include 'equipable' on your pivot call:
return $this->belongsToMany('User', 'user_items')
->withPivot('equipable');
Then you can ask Eloquent if your item is equipable or not:
$item = User::with('items')->get()->find(1)->items->find(2)->pivot->equipable;
Keep two things in mind:
Eloquent uses 'items' as a key internally, so that might interfere.
Whatever method you put before "get()" is part of the db query. Everything after "get()" is handled by PHP on the Object. The latter will be slower in most cases.