Laravel 5.3:hasManyThrough关系

时间:2016-09-02 09:38:19

标签: php laravel model eloquent laravel-5.3

我有以下情况:

location
  id - integer
  network_id - integer (FK)

network
  id - integer
  owner_id - integer (FK)

owner
  id - integer
  name - string

我的位置数据有一个Eloquent模型。现在我要做的是创建一个RESTful API,我可以通过网络模型检索所有者数据。

我尝试使用hasManyThrough没有运气。该模型具有以下关系;

Network - Location = One to Many
Owner - network = One to One

这么多地方属于一个网络,每个网络都有一个所有者。情况总是这样。

我尝试了以下内容。

class Location extends Model 
{
    public function owner() {
       return $this->hasManyThrough('App\Owner', 'App\Network, 'id', 'id);
    }
}

然后在我的资源中返回模型。

class LocationController extends Controller 
{
   public function index() {
      return [
         'data' => Location::with('network', 'owner')->take($limit)->take($offset)->get()
      ];
   }
}

我没有收到错误,但模型没有返回任何所有者,而只返回一个空数组。

有人可以帮助我使用Laravel的Eloquent在这些模型之间建立关系吗?我正在使用Laravel 5.3。

3 个答案:

答案 0 :(得分:1)

不确定您的表格结构是否适合使用hasManyThrough

从我所看到的文档中你需要

location
  id - integer
  network_id - integer

network
  id - integer
  location_id - integer

owner
  id - integer
  network_id - integer
  name - string

然后你可以使用

 return $this->hasManyThrough(
            'App\Owner', 'App\Network',
            'location_id', 'network_id', 'id'
        );

话虽如此,你可以尝试使用hasManyThrough的不同组合来实现它。

return $this->hasManyThrough('App\Owner', 'App\Network, 'owner_id', 'id', 'network_id');

答案 1 :(得分:0)

使用以下代码绑定关系

$option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
if ($option) {
    header("Location: $option");
} 

它解决了你的问题......

答案 2 :(得分:0)

所有者模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Owner extends Model
{    

    public function get_data()
    {
        return $this->belongsToMany('App\Location','App\Network');
    }  

}

通话模型:

<?php

$data=Owner::find(1)->get_data()->select('network_id','location_id')->get();

=&GT;获取网络和位置表数据以使用选择选项