Append data from another model in a model (laravel 5.4) - php

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 ;)

Related

combine table rows if user id is same in foreach loop laravel

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

Laravel 5.2 Eloquent - Finding all id's through multiple relationships

So here are my relationships:
A fund belongs to a planCode
A planCode belongs to a planType
What I need to do is find the fund_id's that are a part of certain plan types. I tried something like this:
$plans = (new 'App\PlanType')->with('planCode.fund')->whereIn('code', ['PENS', 'ANN', 'WEL'])->get();
With this I get the three plan codes with their relationships eager loaded. What I want is a list of all the fund_id's. I tried $plans->lists('planCode.fund.fund_id', 'code') but this returns null for the fund_id. Any ideas?
So if your relationships are like this -
PlanCode has many Funds
Fund belongs to a PlanCode
PlanType has many PlanCodes
PlanCode belongs to a PlanType
Then you can add another relationship like this -
PlanType has many Funds through PlanCodes
UPDATE
After adding a function like this to your PlanType class -
public function funds() {
return $this->hasManyThrough('fund', 'planCode', PT, PC);
}
You can simply access Funds on your PlanType model like this -
$planType->Funds
Take a look at the docs here.
Yep, atefth has it in one. Laravel has a really useful relationship so that you don't have to make repeated queries to the database to get relations of relations. This is the hasManyThrough relationship.
So here, for example, your planType model has many fund models through the planCode model. Your planType model should contain a funds method that looks like this, where PC is the planCode->id column name in the fund table, and PT is the planType->id column in the planCode table:
public function funds() {
return $this->hasManyThrough('fund', 'planCode', PT, PC);
}
You may have to fully namespace your models, depending on the structure of your application.

Laravel 5.1 / Eloquent: How do I use a 3rd table to select from the second table

I have three tables: users, purchase_orders and approvals.
One purchase_order has to be approved by multiple users.
When a new purchase_order gets created, I also create 3 pending approvals belonging to that PO.
The approvals table has a field allowed_user_type that determines who can approve it.
I can't figure out, what is the Eloquent way of selecting the pending purchase orders that can be approved by a specific user, as these are determined from the approvals table.
So far I can pull the pending approvals from the approvals table for a user with the following in the User model.
public function approvals_pending()
{
return $this->hasMany('App\Approval', 'allowed_user_type', 'user_type')
->where('approved', '=', 0);
}
The question is, how do I combine this with a theoretical filter?
I mean ideally, I would love to write:
return $this->hasMany('App\PO')->whereIn('id', '=', $this->approvals_pending()->get()->po_id);
Or something like that...
Any ideas would be greatly appreciated.
OK, for anyone interested I found a solution:
It's very close to what I thought I would have to write.
The lists method basically creates a single array out of the selected field, so it can be plugged-in directly to a whereIn method like so:
return \App\PO::whereIn('id', $this->approvals_pending()->lists('po_id'));
I don't know if this is the most Eloquent way of doing this but it does work.

Is this many-to-many relationship possible in Laravel?

I'm trying to get my head around using polymorphic relationships for a many-to-many relationship between suppliers and products:
products
id
name
suppliers
id
name
product_supplier
id
product_id // belongsToMany easily takes care of this id
supplier_id // and this id
price // this can be fetched using withPivot('price')
deliverymethod_id // I'm having difficulties "joining" this one.
I'm confident in using belongsToMany(), I can easily do something like this:
public function products()
{
return $this
->belongsToMany('Supplier')
->withPivot('price');
}
But the catch here is joining to that third column in the relationship table:
deliverymethods
id
name
I am unsure how to do this. I've been told that Polymorphic Relationships are what I'm after however I'm unsure how to implement them for my situation.
http://laravel.com/docs/4.2/eloquent#many-to-many-polymorphic-relations
According to the documentation, I would have to rename my table columns to include *able_id and *able_type. This is really confusing.
I was expecting laravel to having something like belongsToMany('Supplier')->withAlso('Deliverymethod')
I'm afraid that method does not exist (yet?).
What I fall back to is manually filling in the 3rd relation:
public function products()
{
return $this
->belongsToMany('Supplier')
->withPivot('price', 'delivermethod_id');
}
Now I can access ->pivot->deliverymethod_id on every Product that I get via Supplier.
You could even add a function in your Product model that fills this in automatically:
Class Product ... {
protected $appends = array('deliverymethod');
public function getDeliverymethodAttribute()
{
return Deliverymethod::find($this->pivot->delivermethod_id);
}
Now every time you request a product via it's relation to the supplier, it automatically includes a deliverymethod attribute with the object in it.
(To have it not throw an error when you get a Product directly, just remove the $appends variable from the Product model and call the getDeliverymethodAttribute() method manually whenever you need it.)
Short explanation about polymorphic relations:
Polymorphic relations are for relations, where two models are related to a third model at the same time. So for example both a User and a Product can have a Picture of them. Now, it doesn't make sense to have two models for the pictures (UserPicture and ProductPicture), since they both have the same characteristics. This would be a perfect reason to use a polymorphic relation, where the Picture can both belong to a User or a Product.
However, in your case the Deliverymethod applies directly to the relation between Supplier and Product. So this is not where polymorphic relations would work, but it has instead to be done the way you did it.

Laravel 4 One to One relationship

I would like to have a one to one relationship with a pivot table or by referencing an ID in a table.
I currently have a Films table that has a one to many relationship with a Stock table, each stock item needs a format, however I would like the formats to be a set list of formats so I created a Formats table that only has 2 columns ID and Name
Normally I would just add a Format_ID column to the Stock table however I'm unsure how this would work with the Eloquent ORM or if it's even possible / best practice
Sorry if this is hard to understand, cant quite figure out the best way of explaining it
The structure you desire is pretty standard practice. It's quite possible!
Which Eloquent relationship you'd use depends on the direction of the relationship. Each Stock has one Format (one-to-one). But each Format can be assigned to multiple Stock (one-to-many).
For the former, your Stock Eloquent model would have a hasOne() one-to-one relationship.
class Stock extends Eloquent {
public function format()
{
return $this->hasOne('Format');
}
}
For the latter, your Format eloquent model would have a hasMany() one-to-many relationship.
class Format extends Eloquent {
public function stock()
{
return $this->hasMany('Stock');
}
}
Note that having both of these defined is totally acceptable and normal. It really just depends on which direction you need your relationship to go. If you never need to look up what Stock belongs to a specific Format, you don't need the one-to-many relationship.
Also note that you may need to add a column key parameter if your column names are not easily guessable by Eloquent. E.g.:
return $this->hasOne('Format', 'my_format_id');

Categories