如何在幼虫中使用“belongsTo”关系

时间:2016-06-01 10:07:40

标签: php laravel-5

我有两个模型'用户'和'医生'我想要使用eloquent relatonahiops hasMany和belongsaTo将它们联系起来如下

This is the model for users
   protected $fillable = [
    'name',
    'email',
    'password',
    'role_id',
    'active_user',
];

public function doctor()
{
    return $this->hasMany('App\Doctor','user_id');
}

以及医生的模型如下      protected $ table =“doctors”;

protected $fillable = [
    'role_id',
    'user_id',
    'name',
    'date',
    'gender',
    'specialization',
    'state',
    'country',
    'email',
    'mobile',
    'phone',
    'address',
    'password',
    'pic'

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

现在我有一张桌子,我使用下面的@foreach语句显示医生

<table id="example" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
    <thead >
    <tr >
        <th>
            S/N
        </th>
        <th>
            Picture
        </th>

        <th style="text-align: center;">
            Name
        </th>

        <th style="text-align: center;">
            Specialization
        </th>

        <th  style="text-align: center;">
            Phone Number
        </th>

        <th  style="text-align: center;">
            Status
        </th>


        <th style="text-align: center;">
            Book
        </th>
        {{--<th style="text-align: center;">--}}
        {{--Message--}}
        {{--</th>--}}

    </tr>
    </thead>
    <tbody>
    <?php $c=0;?>
    @foreach($doctors as $dr)
        <tr style="padding: 10px; text-align: center;">
            <td>{{++$c}}</td>
            <td>
                <img src='{{url("assets/images/doctors_pic_uploads/".$dr->pic)}}' style="height:40px; width:40px;" class="img-circle">
            </td>
            <td style="padding: 20px;">{{$dr->name}}</td>
            <td style="padding: 20px; ">{{$dr->specialization}}</td>
            <td style="padding: 20px;">{{$dr->phone}}</td>
            <td style="padding: 20px;">

            </td>
            <td style="padding: 20px;">
                <input type="radio" name="book" value="{{$dr->id}}">

            </td>
           This is where i want to show if they are offline or online
        </tr>
    @endforeach


    </tbody>
</table>

我的控制器位于

之下
public function BookDoctors(){
    if(!Auth::check()) {
        return Redirect::to('admin/login');
    }
    $opt=User::findOrFail(Auth::User()->id)->operator->first();
    $doctors = Doctor::all();
    $patients = PatientInfo::all();
    return view('Others.Operator.Appointment.book_doctors')->with(compact('opt','doctors','patients'));

}

现在的挑战是我希望从用户迁移中获取“active_user”字段,并使用laravel中的belongsTo关系将其包含在表头“状态”的表单中

2 个答案:

答案 0 :(得分:1)

Laravel Documentation One to many Relation

$dr->user->get()->all();

应该返回该医生的所有用户。

答案 1 :(得分:0)

在查询中获取用户详细信息

$doctors = Doctor::with('user')->get();

在您的视图文件中

<td>{{$dr->user->active_user}}</td>