大佬教程收集整理的这篇文章主要介绍了Laravel 7 传递关系并访问最终表,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
嗨,我有这 4 个表:用户、菜肴、dish_order、订单。
users:有些字段没有外键
菜肴
dish_order
orders:有些字段没有外键
这些是模型:用户、菜品、订单。
用户:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'email','password','company_name','address','vat','phone_number','opening_info','website','Vote_average'
];
/**
* The attributes that should be hIDden for arrays.
*
* @var array
*/
protected $hIDden = [
'password','remember_token',];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verifIEd_at' => 'datetiR_944_11845@e',];
public function dishes() {
return $this -> hasmany(dish::class);
}
public function typologIEs() {
return $this -> belongsToMany(Typology::class);
}
}
菜:
class dish extends Model
{
protected $fillable = [
'name','desc','price','visible','type',];
public function user() {
return $this -> belongsTo(User::class);
}
public function orders() {
return $this -> belongsToMany(Order::class);
}
}
顺序:
class Order extends Model
{
protected $fillable = [
'code','CUSTOMER_NAME','customer_address','customer_phone','date','status','@R_603_10586@l_price',];
public function dishes() {
return $this -> belongsToMany(dish::class);
}
}
现在在控制器中,我需要找到与用户相关的所有订单(例如 ID 18)。 我试过了,它奏效了,但在这种情况下,我丢失了与订单相关的所有菜肴。
$loggedUserID = Auth::user() -> ID;
$orders = DB::table('users')
-> join('dishes','users.ID','=','dishes.user_iD')
-> join('dish_order','dishes.ID','dish_order.dish_ID')
-> join('orders','orders.ID','dish_order.order_ID')
-> SELEct('orders.*',DB::raw('COUNT(dishes.ID) as dishes'))
-> groupBy('orders.ID')
-> where('user_iD',$loggedUserID)
-> get();
结果:订单数组/集合,每个订单内部都应该有一个数组,其中包含与订单相关的菜肴列表。如果可能,我该怎么做?谢谢。
您已经在模型中建立了雄辩的关系,因此您可以利用这些关系。
$orders = Order::whereHas('dishes',function($query) {
$query->where('user_id',auth()->id());
})
->with(['dishes' => function($query) {
$query->where('user_id',auth()->id());
}])
->get();
第一部分whereHas(...)
将只获取登录用户有菜的订单。
第二部分 with(...)
将只获取属于登录用户的菜肴。
然后你可以迭代订单和菜肴
foreach($orders as $order) {
$order->dishes;
}
以上是大佬教程为你收集整理的Laravel 7 传递关系并访问最终表全部内容,希望文章能够帮你解决Laravel 7 传递关系并访问最终表所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。