繁体   English   中英

Laravel 5.3:hasManyThrough关系

[英]Laravel 5.3: hasManyThrough relationship

我有以下情况:

location
  id - integer
  network_id - integer (FK)

network
  id - integer
  owner_id - integer (FK)

owner
  id - integer
  name - string

我的位置数据有一个雄辩的模型。 现在,我要做的是创建一个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。

不确定您的表结构是否适合使用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');

用下面的代码绑定关系

class Location extends Model
{
 public function network()
 {
    return $this->hasMany('App\Network');
 }
}


class Network extends Model
{

 public function owner()
 {
    return $this->hasOne('App\Owner');
 }
}

它解决了您的问题...

车主型号:

<?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();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM