Laravel 4:雄辩的关系获取所有数据

时间:2022-10-16 08:44:30

I have 2 relationship data table; users table and memberdetails table.

我有2个关系数据表; users表和memberdetails表。

Users.php

class Users extends Eloquent{

    public function memberdetails()
    {
        return $this->hasOne('Memberdetails','user_id');
    }
}

Memberdetails.php

class Memberdetails extends Eloquent{

    public function user()
    {
        return $this->belongsTo('Users','user_id');
    }
}

When I try to retrieve data, with $data = User::find($id); I only get data from users table.

当我尝试检索数据时,使用$ data = User :: find($ id);我只从users表中获取数据。

Example of my blade form:

刀片形式示例:

{{-- User's Name, stored on user table --}}
{{ Form::text('name',null, array('id'=>'name','class'=>'form-control','required')) }}

{{-- User's address, stored on member table --}}
{{ Form::text('address',null, array('id'=>'address','class'=>'form-control','required')) }}

When I visit, localhost/user/2/edit/, the name field is populated, but address field is empty. How can I retrieve data from both tables and put into a form for editing?

当我访问localhost / user / 2 / edit /时,将填充名称字段,但地址字段为空。如何从两个表中检索数据并将其放入表单进行编辑?

Thank you.

2 个解决方案

#1


22  

You could use eager loading.

您可以使用预先加载。

$user = User::with('memberdetails')->find($id);

Using this, you will automatically get the memberdetails when retrieving the user. Then you can use $user->memberdetails

使用此选项,您将在检索用户时自动获取memberdetails。然后你可以使用$ user-> memberdetails

Using eager loading, you do only one query to the DB so it should be the preferred way. If you dont use the with('memberdetails'), you will perform a second query when accessing the memberdetails.

使用预先加载,您只对DB执行一次查询,因此它应该是首选方式。如果你不使用with('memberdetails'),你将在访问memberdetails时执行第二个查询。

#2


0  

After getting the user instance, access the relationship, then you can access the other class properties

获取用户实例后,访问该关系,然后您可以访问其他类属性

$user = User::find($id);
$userData = $user->memberdetails;

#1


22  

You could use eager loading.

您可以使用预先加载。

$user = User::with('memberdetails')->find($id);

Using this, you will automatically get the memberdetails when retrieving the user. Then you can use $user->memberdetails

使用此选项,您将在检索用户时自动获取memberdetails。然后你可以使用$ user-> memberdetails

Using eager loading, you do only one query to the DB so it should be the preferred way. If you dont use the with('memberdetails'), you will perform a second query when accessing the memberdetails.

使用预先加载,您只对DB执行一次查询,因此它应该是首选方式。如果你不使用with('memberdetails'),你将在访问memberdetails时执行第二个查询。

#2


0  

After getting the user instance, access the relationship, then you can access the other class properties

获取用户实例后,访问该关系,然后您可以访问其他类属性

$user = User::find($id);
$userData = $user->memberdetails;