我试图创建一个简单的Laravel 5应用程序用于测试目的,我仍然在努力通过模型关系显示所需的数据。 当我通过工匠修补匠测试模型关系时,一切正常。 在我的索引视图中,一切都很好......直到我使用第二个链接模型,这给了我主题中的错误。
以下是我的表格(迁移):
Schema::create('orders', function(Blueprint $table)
{
$table->increments('id');
$table->timestamps();
$table->string('status');
});
Schema::create('products', function(Blueprint $table)
{
$table->increments('id');
$table->integer('order_id')->unsigned();
$table->timestamps();
$table->string('name');
$table->string('sn');
});
Schema::create('services', function(Blueprint $table)
{
$table->increments('id');
$table->integer('order_id')->unsigned();
$table->timestamps();
$table->string('name');
$table->string('type');
});
以下是我的3个型号:
//文件:App \ Order.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model {
public function products()
{
return $this->hasMany('App\Product');
}
public function services()
{
return $this->hasMany('App\Service');
}
}
//文件:App \ Product.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
public function order()
{
return $this->belongsTo('App\Order');
}
}
//文件:App \ Service.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Service extends Model {
public function order()
{
return $this->belongsTo('App\Order');
}
}
//我的简单控制器OrdersController.php
public function index()
{
$orders = Order::all();
return view('orders.index', compact('orders'));
}
最后我的观点&#34; /resources/views/orders/index.blade.php"
<ul>
@foreach( $orders as $order )
<li>
Order# {{ $order->id }} - //this line is OK
{{$order->products->first()->name}} - //this line is OK
{{$order->services->first()->name}} - //as soon as I add this line, I get the error!
</li>
@endforeach
</ul>
=&GT;难道我做错了什么?是不是可以从2&#34;外部&#34;中检索数据。同一视图中的模型? 非常感谢你的帮助!
答案 0 :(得分:2)
每个订单是否至少分配了一项服务?我的猜测不是,在这种情况下你应该把它包装在if语句中:
@foreach( $dossiers as $dossier )
<li>
Order# {{ $order->id }}
@if($product = $order->products->first())
{{ $product->name }}
@endif
@if($service = $order->services->first())
{{ $service->name }}
@endif
</li>
@endforeach