Laravel 填充外键数据

Laravel populate foreign key data

嗨,我是 Laravel 的新手,正在尝试用 Laravel Lumen 制作 RESTFul api 我已经安装了 laravel 和 Lumen,我的版本是

Laravel Framework version Lumen (5.2.6) (Laravel Components 5.2.*)

现在我还安装了 https://github.com/jarektkaczyk/eloquence 用于映射数据库列名称,我已经完成了

联系人模型

namespace App;
use Illuminate\Database\Eloquent\Model;
use Sofa\Eloquence\Eloquence; // base trait
use Sofa\Eloquence\Mappable; // extension trait

class Contacts extends Model {
    use Eloquence, Mappable;
    protected $table = 'contacts';
    protected $primaryKey = 'idcontacts';
    protected $visible = ['firstname', 'lastname','idorganization'];
    protected $maps = [
        'firstname'=> 'firstName',
        'lastname' => 'lastName'
    ];

    public function organization() {
        return $this->hasOne('App\Organization','idorganization');
    }
}

组织模型

namespace App;
use Illuminate\Database\Eloquent\Model;

class Organization extends Model {

    protected $table = 'organization';
    protected $primaryKey = 'idorganization';
    protected $visible = ['organization_name', 'website','website','phone','num_employes','industry'];

    public function contacts() {
        return $this->belongsTo('App\Contacts', 'idorganization');
    }
}

联系人的控制器看起来像

namespace App\Http\Controllers;
use App\Contacts;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class ContactsController extends Controller
{
    public function getAll() {
        $contacts = Contacts::all();
        return response()->json($contacts);
    }
}

但响应不会使用来自组织的模型列填充 idorganization

我还试过 $contacts = Persona::with('organization')->all();

但它returns错误为

Call to undefined method Sofa\Eloquence\Query\Builder::all()

如果我删除联系人模型中的 Sofa\Eloquence 和特征,它仍然不起作用。

请让我知道我遗漏了一些明显的东西

没有关系我得到的响应是

[
 {
    "firstname":"Abhik",
    "lastname":"Chakraborty",
    "idorganization":"1"
 },
 {
    "firstname":"John",
    "lastname":"Martin"
    "idorganization":"1"
 }
]

预期结果为

[
     {
        "firstname":"Abhik",
        "lastname":"Chakraborty",
        "organization":{
          "organization_name": "foo"
          "website": "bar"
          ..................
        }
     },
     {
        "firstname":"John",
        "lastname":"Martin"
        "organization":{
          "organization_name": "foo"
          "website": "bar"
          ...............
        }
     }
 ]

当您调用 all() 时,您的响应未填充 idorganization 字段的原因是默认情况下关系是延迟加载的,这意味着关系数据将在您实际访问它们时加载。

为了完成你想要的,你需要使用 get() 方法而不是 all() 当你使用 with() 方法时,它被命名为 eager loading.

替换为:

Persona::with('organization')->all();    

有:

Persona::with('organization')->get();