无法达到预期的效果。我正在尝试获取我已定义的用户集合模型,对已分配的ID进行排序并获取具有该ID的产品。
我似乎无法将其传回控制器。如果我只是回应我得到我想要的东西,但我更愿意将它添加到集合然后我可以从一个集合(我需要的一切)调用它而不是调用两个数组。
//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循环并获取$ product-> 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);
}
}
答案 0 :(得分:2)
User::find(1)->collection
如何定义?您可以发布模型以显示用户,集合?和产品之间的关系吗?
尝试设置hasManyThrough关系,如下所示:
/**
* Get all of the products for the user.
*/
public function products()
{
return $this->hasManyThrough('App\Product', 'App\Collection');
}
这将导致集合对象包含用户的所有产品。