Reputation: 8108
I am creating a quote. My tables look something like this:
quote:
PK:id
name
FK:client_id
FK:user_id
created_at
quoteSkus:
PK:id
FK:quote_id
FK:sku_id
price
sku:
PK:id
name
created_at
My relationships look like this:
Quote.php
public function skus(){
return $this->hasMany('\App\Http\Models\Quotesku','quote_id','id');
}
public function client(){
return $this->hasOne('\App\Http\Models\Client', 'id','client_id');
}
public function contact(){
return $this->hasOne('\App\Http\Models\Contact', 'id','contact_id');
}
QuotaSkus.php
public function sku(){
return $this->hasOne("\App\Http\Models\Sku","id","sku_id");
}
public function quote(){
return $this->hasOne("\App\Http\Models\Quote","id","quote_id");
}
sku.php
public function lastUsage(){
return $this->hasOne('\App\Http\Models\Quotesku','sku_id','id');
}
I want to get the price that was set for this sku
in this clients last quote.
This query will give me just that:
SELECT *
FROM `skus` as s
RIGHT JOIN quoteskus as qs on qs.sku_id = s.id
RIGHT JOIN quotes as q on q.id = qs.quote_id
where s.id = 236
AND q.client_id = 2
order by q.created_at DESC
Is it possible to set this up with eloquent relationships? So I will be able to
$sku = new Sku();
$sku->find(1);
$sku->lastUsage->price;
or
$sku->lastUsage(client_id)->price;
Sorry for the code dump, I tried to sum it up as much as I could.
Any advice would help. Thank you :)
Upvotes: 1
Views: 1272
Reputation: 2932
You can use the following
$sku = Sku::find(1);
$quotesku = $sku->lastUsage->price;
And sku.php
public function lastUsage(){
return $this->hasMany('\App\Http\Models\Quotesku','sku_id','id')->orderBy('created_at', 'desc')->first();
}
Upvotes: 3
Reputation: 4359
Here should be what you want:
public function lastUsageByClient($client_id) {
return $this->join('quoteSkus', 'sku.id', '=', 'quoteSkus.sku_id')
->join('quote', 'quote.id', '=', 'quoteSkus.quote_id')
->select('sku.*', 'quoteSkus.price')
->where('quote.client_id', $client_id)
->orderBy('quote.created_at', 'desc')
->first();
}
Not pretty, but should work.
EDIT:
public function lastUsage() {
return $this->hasOne('\App\Http\Models\Quotesku','sku_id','id')
->join('quote', 'quote.id', 'quoteSkus.quote_id')
->orderBy('quote.created_at', 'desc');
}
You might want to specify which columns to pull here as well.
Upvotes: 1