2017-06-15 76 views
1

無法實現預期的結果。我試圖獲得我定義的用戶集合模型,通過分配的ID進行排序,並獲取具有該ID的產品。循環收集,構建數組,與laravel聯合收集

我似乎無法通過此回控制器。如果我只是回聲我得到我想要的東西,但我更願意將它添加到集合中,然後我可以從一個集合(我需要的所有東西)調用它,而不是調用兩個數組。

//get collection relationship 
     $collection = User::find(1)->collection; 
     // product number id 
     $products = $collection->products; 
     // remove ',' character 
     $productId = explode(',', $products); 
     //count many products 
     $productCount = count($productId); 


     // collection 
     foreach ($productId as $key => $value) { 
      // dd($products); 
      $array = $this->getArray(str_split($value)); 
      // array 
      foreach($array as $product){ 
       $name = $product->name; 
       $img = $product->image_path; 
       $price = $product->price; 


       $productFinal = $name . ' ' . $img . ' ' . $price; 
       //price 
       echo $productFinal; 

      } 
     } 

這將返回相關的所有產品清單,我只是努力再追加一條的集合或其他陣列,並傳遞到刀片,這樣我可以做$ productFinal foreach循環並獲得$產品 - > name等。我想將它追加到$ collection,但是push()或merge()不成功。 非常感謝和平:)

編輯: 收集模型參考

class Collection extends Model 
{ 
protected $id = ['id']; 

public function user() 
{ 
    return $this->belongsTo(User::class); 
} 
public function products() 
{ 
    return $this->hasMany(Product::class); 
} 
} 

class Product extends Model 
{ 
// uses carbon instance from model $dates 
protected $dates = ['created_at']; 
protected $id = ['id']; 

public function setPublishedAtAttribute($date) 
{ 
    $this->attributes['created_at'] = Carbon::createFromFormat('Y-m-d', $date); 
} 
/** 
* Example mutators for the scopes 
* @param [type] $query [description] 
* @return [type]  [description] 
*/ 
public function scopePublished($query) 
{ 
    $query->where('created_at', '<=', Carbon::now()); 
} 

public function scopeUnpublished($query) 
{ 
    $query->where('created_at', '>', Carbon::now()); 
} 

/** 
* Return category for product bread controller 
* @return [type] [description] 
*/ 
public function category(){ 
    return $this->belongsTo(ProductCategory::class); 
} 


    } 

回答

2

User::find(1)->collection是如何定義的?你可以發佈你的模型來顯示用戶,集合?和產品之間的關係嗎?

嘗試建立像這樣一個hasManyThrough關係:

/** 
* Get all of the products for the user. 
*/ 
public function products() 
{ 
    return $this->hasManyThrough('App\Product', 'App\Collection'); 
} 

這將導致包含所有的產品,爲用戶提供集合對象。

+0

我已更新,因此我認爲您現在可以看到它。 – m33bo

+0

因此,您正在通過集合模型查找屬於用戶的所有產品,據我瞭解? – btl

+0

是的,並且希望將每個產品附加到集合中,以代替產品ID所在的位置,並且擁有所有產品的陣列 – m33bo