Laravel 5 / Eloquent:尝试从链接表中获取值时出错

Laravel 5 / Eloquent: error when trying to get values from linked tables

我正在尝试创建一个简单的 Laravel 5 应用程序用于测试目的。一切似乎都设置正确(数据库、表等),我的模型关系也正常(使用 php artisan tinker 测试)。 我仍然收到错误 "Undefined property..." 并且无法理解如何从视图中的其他链接表中获取值...

/resources/views/orders/index.blade.php

<ul>
@foreach( $orders as $order )
<li>Order # {{ $order->id }} - {{$order->status}} - {{$order->products->name}} - </li>
@endforeach
</ul>

=> 我做错了什么吗?如何获取与订单关联的产品名称?

OrdersController.php
public function index()
{
$orders = Order::all();
return view('orders.index', compact('orders'));
}

这是我的表(迁移):

public function up()
{
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');
});

这是我的 2 个模型:

//文件:App\Order.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model {

public function products()
{
return $this->hasMany('App\Product');
}

}

//文件:App\Product.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model {

public function order()
{
return $this->belongsTo('App\Order');
}
}   

非常感谢您的帮助!

这里的问题是 $order->products 给你的是产品集合而不是单一产品。您可以使用 $order->products->first()->name 或迭代产品来获取每个产品的名称。

在您的订单控制器中,您需要编写 with 来检索关系数据

public function index()
{
      $orders = Order::with('products')->all();
      return view('orders.index', compact('orders'));
}

如果您想一直按订单检索产品,您可以在模型中使用 with 像这样指定它

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model {

protected $with = 'products';

    public function products()
    {
         return $this->hasMany('App\Product');
    }

}

现在,当您检索订单时,它总是检索使用 with 指定的关系数据,即产品

查看

在您看来,您可以访问这样的产品,因为一个订单有很多产品

    <ul>
    @foreach( $orders as $order )
    <li>Order # {{ $order->id }} - {{$order->status}} - 
     @foreach( $order->products as $product )
         {{$product->name}}
     @endfor
    - </li>
    @endforeach
    </ul>

我建议你应该 read more 关于你正在开发的框架。

第 1 步:

您应该将您的模型 class 命名为单数名称
例如 'category' ,并将 table 名称定义为 tbl_products_category

    class category extends Eloquent {

     protected $table = 'tbl_products_category';

    } 

第二步

然后您可以使用 Eloquent 智能方法以干净的代码 select 您的数据。
在你的 route.php 文件上。

   $product_categories =
   category::where('tbl_product_category_status', '=', 1)->get();

然后将此对象分配给您的视图:

$view = View::make('greeting')
->with('product_categories',$product_categories);

终于

将此代码放在您的视图中

    @foreach ($product_categories as $category)
    <li><a href="{{$category->tbl_product_category_id;}}">{{$category
    ->tbl_product_category_name;}}"</a></li>
    @endforeach