雄辩的交往不起作用返回试图获取非对象的属性

时间:2019-07-28 05:40:16

标签: laravel eloquent laravel-blade

产品名称/标题表列未与代码中使用的“雄辩的关系”一起出现

<td>@if(is_null($order->products)) No Product 
    @else {{$order->products->title}} 
    @endif
</td> 
<tbody>
   @foreach($orders as $order)                     
       <tr class="">               
        @endif
         <td>{{$order->customer_email}}</td>
         <td>{{$order->customer_name}}</td>
         <td>{{array_sum($order->quantities)}}</td>
         <td>{{$order->customer_city}}</td>
         <td>@if(is_null($order->products)) No Product 
             @else {{$order->products->title}} 
             @endif
         </td>
         <td>{{$order->method}}</td>
        </tr>
   @endforeach
</tbody>

这是我的产品型号和![数据库结构] https://i.postimg.cc/BbzdS0Pg/productmain.png enter image description here

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'title', 'category', 'tags', 'description', 'sizes', 'price', 'previous_price', 'stock',
        'feature_image', 'policy', 'featured', 'views', 'created_at', 'updated_at', 'status'
    ];

    public static $withoutAppends = false;

    public function vendor()
    {
        return $this->belongsTo('App\Vendors', 'vendorid', 'id');
    }

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

这是我的订单模型和![数据库结构] https://i.postimg.cc/zXVy0FzZ/ordertable.png enter image description here


namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $fillable = [
        'customerid', 'products', 'quantities', 'method', 'shipping', 'pickup_location', 'pay_amount', 
        'txnid', 'charge_id', 'order_number', 'payment_status', 'customer_email', 'customer_name', 
        'customer_phone', 'customer_address', 'customer_city', 'customer_zip', 'shipping_name', 
        'shipping_email', 'shipping_phone', 'shipping_address', 'shipping_city', 'shipping_zip', 
        'order_note', 'booking_date', 'status'
    ];

    public $timestamps = false;

    public static $withoutAppends = false;

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

试图获取非对象的属性

1 个答案:

答案 0 :(得分:0)

您的products()是对象的集合,而您无法获得其中的title,如果要显示订单产品,我建议采用这种方式:

<td>
    @if(is_null($order->products)) 
    No Product 
    @else
        @foreach($order->products()->get() as $product)
             {{$product->title}} - 
        @endforeach
    @endif
</td>