laravel中的一对多关系显示在视野中

时间:2018-05-28 08:14:17

标签: php laravel

我正在研究laravel电话簿应用程序我希望每个电话簿都有一个客户端但是客户端属于许多电话簿我现在在我的电话簿表中有一个名为client_id的列当我设置关系时如何在控制器中使用它们并传递它进入视图作为对象,这是我的一些代码

电话簿控制器

public function index(){

$phonebooks = Phonebook::all();
$client = Phonebook::find(?dont know if its right place for it?)->client;
return view('admin.phonebooks.index',compact('phonebooks',$phonebooks),compact('client',$client));}

电话簿型号

class Phonebook extends Model{protected $fillable = ['title','description','client_id','calldate','rememberdate'];public function client() {
return $this->hasOne('App\Client','id');}    }

电话簿数据库迁移

Schema::create('phonebooks', function (Blueprint $table) {
    $table->increments('id');
    $table->text('title');
    $table->longText('description');
    $table->integer('client_id');
    $table->dateTime('calldate');
    $table->dateTime('rememberdate');
    $table->timestamps();
});

和客户端数据库迁移

Schema::create('clients', function (Blueprint $table) {
    $table->increments('id');
    $table->text('title');
    $table->longText('description');
    $table->integer('fax');
    $table->text('adrress1');
    $table->integer('telephone1');
    $table->timestamps();
});

以及我想在其中显示的视图

@foreach($phonebooks as $phonebook)
<tr>
    <th scope="row">{{$phonebook->id}}</th>
    <th scope="row">{{$phonebook->title}}</th>
    <td><a href="/admin/phonebooks/{{$phonebook->id}}">{{$phonebook->description}}</a></td>
    <td>{{$phonebook->calldate}}</td>
    <td>{{$phonebook->created_at->toFormattedDateString()}}</td>

    <td>{{$client->title}}</td>
    <td>
        <div class="btn-group" role="group" aria-label="Basic example">
            <a href="{{ URL::to('admin/phonebooks/' . $phonebook->id . '/edit') }}">
                <button type="button" class="btn btn-warning">edit</button>
            </a>&nbsp;
            <form action="{{url('admin/phonebooks', [$phonebook->id])}}" method="POST">
                <input type="hidden" name="_method" value="DELETE">
                <input type="hidden" name="_token" value="{{ csrf_token() }}">
                <input type="submit" class="btn btn-danger" value="delete"/>
            </form>
        </div>
    </td>
</tr>@endforeach

2 个答案:

答案 0 :(得分:1)

您在电话簿中拥有客户端属性,使用它

<td>{{$phonebook->client->title}}</td>

答案 1 :(得分:1)

我建议加载所有客户端,以便更加高效,您可以在docs

上阅读原因

您可以在控制器上执行此操作:

public function index()
{
    $phonebooks = Phonebook::with('client')->get();
    return view('admin.phonebooks.index',compact('phonebooks',$phonebooks);
}

然后在您的视图中,您可以访问电话簿客户端,这要归功于您定义的关系:

@foreach ($phonebooks as $phonebook) 
    {{ $phonebook->client->title }}
@endforeach