I have a two Models: a Deal is started on one system by customers, and a Sale is started on another system by a salesman. I have an intermediate table dms_matches
that forms a many-to-many relationship between those models, and includes a confidence score.
Customers can start many deals, the confidence score measures how likely the customer Deal is the exact one that initiated the final Sale transaction. (e.g., one system says first name is "Joe" and the other says "Joseph", or customer got upsold so Sale contains a related but different product than Deal)
I have a working many-to-many relationship on Sale to return all matched Deals:
public function deals()
{
return $this->belongsToMany('App\Models\Deal', 'dms_matches', 'dms_sale_id')
->orderBy('dms_matches.confidence', 'DESC')
->withPivot('confidence');
}
Now I would like a relationship that returns the exactly one Deal with the highest confidence score. (I want a relationship so I can get eager loading and caching.)
This works, but returns a collection of length one:
public function best_deal()
{
return $this->deals()->limit(1);
}
This works, but isn't a relationship, so it doesn't work with eager loading.
public function getBestDealAttribute()
{
return $this->deals()->first();
}
How can I build something that behaves like a hasOne
or belongsTo
relationship, but uses an intermediate table?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire