Laravel如何基于两个模型或列定义关系?
我有以下资料:Laravel如何基于两个模型或列定义关系?,laravel,laravel-5,laravel-5.8,Laravel,Laravel 5,Laravel 5.8,我有以下资料: //users table id name email remeber_token role_id 产品的价格将根据用户角色而变化,如何定义正确的关系,以便在blade I中执行以下操作: $product->price 这将根据用户和产品返回正确的价格?我相信,当你说用户角色时,你指的是认证用户的角色 最简单的方法是在产品模型上定义HasOne关系: class Product { public function price() { r
//users table
id
name
email
remeber_token
role_id
产品的价格将根据用户角色而变化,如何定义正确的关系,以便在blade I中执行以下操作:
$product->price
这将根据用户和产品返回正确的价格?我相信,当你说用户角色时,你指的是认证用户的角色 最简单的方法是在产品模型上定义HasOne关系:
class Product
{
public function price()
{
return $this->hasOne(Price::class)->where('role_id', auth()->user()->role_id)
}
}
因此,从这个角度来看,你可以简单地说:
// Lets use optional() because there may not be any price for that product and user.
optional($product->price)->price
如果涉及到许多产品,那么使用将更有意义
class ProductsController extends Controller
{
public function index()
{
$products = Product::addSelect(['right_price' => Price::select('price')
->whereColumn('product_id', 'products.id')
->where('role_id', auth()->user()->role_id)
->limit(1)
])->get()
return view('products.index', compact('products'));
}
}
然后在视图中:
@foreach($products as $product)
<p>{{$product->right_price}}</p>
@endforeach
@foreach($products作为$product)
{{$product->right_price}
@endforeach
欲了解更多信息,请查看
// Lets use optional() because there may not be any price for that product and user.
optional($product->price)->price
class ProductsController extends Controller
{
public function index()
{
$products = Product::addSelect(['right_price' => Price::select('price')
->whereColumn('product_id', 'products.id')
->where('role_id', auth()->user()->role_id)
->limit(1)
])->get()
return view('products.index', compact('products'));
}
}
@foreach($products as $product)
<p>{{$product->right_price}}</p>
@endforeach