2017-06-15 73 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