Laravel填充外键数据

时间:2016-05-01 19:04:40

标签: laravel eloquent relationships lumen lumen-5.2

您好我是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();

但它返回错误

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"
          ...............
        }
     }
 ]

1 个答案:

答案 0 :(得分:1)

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

要使用get()方法而不是all(),当您使用名为eager loadingwith()方法时,您需要使用Persona::with('organization')->all(); 方法。

替换它:

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

使用:

{{1}}