Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel 5.2有许多关系问题_Php_Laravel_Laravel 5_Eloquent_Laravel 5.2 - Fatal编程技术网

Php Laravel 5.2有许多关系问题

Php Laravel 5.2有许多关系问题,php,laravel,laravel-5,eloquent,laravel-5.2,Php,Laravel,Laravel 5,Eloquent,Laravel 5.2,我有3个表格:订单、代码、事件 我希望能够提取订单中的所有事件,但有一个充当透视表的中间表。我一直在尝试使用hasManyThrough和belongtomany(以及with pivot)而没有任何运气 示例: public function events() { return $this->belongsToMany('events'); // tried this, fails return $this->hasManyThrough('events', 'co

我有3个表格:订单、代码、事件

我希望能够提取订单中的所有事件,但有一个充当透视表的中间表。我一直在尝试使用
hasManyThrough
belongtomany
(以及
with pivot
)而没有任何运气

示例:

public function events()
{
    return $this->belongsToMany('events'); // tried this, fails
    return $this->hasManyThrough('events', 'codes'); // tried this, fails
    return $this->hasManyThrough('events', 'codes', 'event_id', 'id'); // tried this, fails
}
任何指针都会很棒

这是一个设置。首先,第一个参数是相关类的名称。其次,由于透视表不遵循Laravel命名约定,因此需要在关系定义中指定透视表的名称:

public function events()
{
    // first parameter is the name of the related class
    // second parameter is pivot table name
    return $this->belongsToMany(Event::class, 'codes');
}
使用此设置,您可以执行以下操作:

// get an order
$order = Order::first();

// has all the events related to an order
$events = $order->events;

有很多方法可以做到这一点。我会展示一个你能完成的

Order.php
模型中

public function codes(){
   return $this->has('App\Http\Code');
}
public function orders(){
   return $this->belongsTo('App\Http\Order');
}

public function events(){
   return $this->hasMany('App\Http\Event');
}
public function codes(){
   return $this->belongsTo('App\Http\Code');
}
code.php
模型中

public function codes(){
   return $this->has('App\Http\Code');
}
public function orders(){
   return $this->belongsTo('App\Http\Order');
}

public function events(){
   return $this->hasMany('App\Http\Event');
}
public function codes(){
   return $this->belongsTo('App\Http\Code');
}
Event.php
模型中

public function codes(){
   return $this->has('App\Http\Code');
}
public function orders(){
   return $this->belongsTo('App\Http\Order');
}

public function events(){
   return $this->hasMany('App\Http\Event');
}
public function codes(){
   return $this->belongsTo('App\Http\Code');
}
然后在控制器中,调用它们以获取所需的数据

在您的情况下,您可以按以下方式进行:

$orders = Order::with(['codes' => function($q){
    $q->with('events');
})->get();
也许你可以用嵌套的方式得到它们(我不确定这一点,因为我在发布之前没有尝试过):

$orders=Order::with('code.events')->get()

放入
返回$orders以查看查询

享受吧