I have products table and countries table, they suppose to be in a many to many relation to each other but to contain additional parameter for the relation.
so in the products there is the product id, name
in the countries there is the country id, name
in the product_country there is country_id, product_id, price
product model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
/**
* Get the countries for the product.
*/
public function countries()
{
return $this->belongsToMany('Country');
}
}
country model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
/**
* Get the countries for the product.
*/
public function products()
{
return $this->belongsToMany('Product');
}
}
so i know i can use ->withPivot('price') to add it to the pivot relation but what i can't figure out - is what is the best way to query the list of products for example by country, maybe my structure is wrong but i would like eventually to be able to get all the products with their prices of course for a specific country.
it feels like i need to do so much work to get a price for a product by country.
Country::find(1)->products->first()->pivot->price