簡體   English   中英

Laravel 錯誤:此集合實例上不存在屬性 [名稱]

[英]Laravel error: Property [name] does not exist on this collection instance

我正在嘗試使用 Laravel 資源集合為每個訂單找到一個合作伙伴。 但這會引發錯誤:

Property [name] does not exist on this collection instance

我通過這種方式獲得partners

訂單_product.php

//...
class Order_product extends Model
{
    protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];

public function partner()
  {
   return $this->hasManyThrough(
         'App\Partner', 'App\Order',
      'partner_id', 'id', 'order_id');
        //orders  partners  order_products
   }
//...

資源\\Order_product.php

class Order_product extends JsonResource
{
   public function toArray($request)
    {
     return [
            'id'         => $this->id,
            'order_id'   => $this->order_id,
            'product_id' => $this->product_id,
            'quantity'   => $this->quantity,
            'price'      => $this->price,
            'status'     => $this->order->status,
          'product_name' => $this->prod->name,

           //return error
          'partner_name' => $this->partner->name,

         ];
/*
//this method return:
//Invalid argument supplied for foreach() {"exception":"[object]... 

$partners = [];

        foreach($this->collection as $partner) {

             array_push($partners, [

                // 'partner_name' => $this->partner->name
             ]);

        }

        return $partners;
*/
    }
}

每個訂單都有一個合作伙伴名稱。 以后我會把它們分組,但現在我只需要輸出partner_name

當您使用hasManyhasManyThrough時是關系,它會返回一個集合,因此您應該在foreach 中使用它或與索引一起使用

return [
'product_name' => $this->prod->first()->name,  //first array in collection using first()
   ];

或者

return [
'product_name' => $this->prod[0]->name,  //first array in collection using index
   ];

或者您可以在foreach 中編寫此代碼!

當您使用hasManyThroughhasMany laravel 關系時,會返回Illuminate\\Database\\Eloquent\\Collection Eloquent Illuminate\\Database\\Eloquent\\Collection Instance。

如果您想獲得名稱,您必須擁有一個Model實例。

解決方案 1 : $this->parthner->first()->name

解決方案 2 :看這個hasOneThough


public function partner(){
   return $this->hasOneThrough(
         'App\Partner', 'App\Order',
      'partner_id', 'id', 'order_id');
}

取決於你的應用邏輯

希望這對你有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM