难以达到预期的结果。我正在尝试获取我定义的用户集合模型,对分配的 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);
}
}
如何定义User::find(1)->collection
?您能否发布模型以显示用户、集合和产品之间的关系?
尝试像这样设置一个 hasManyThrough 关系:
/**
* Get all of the products for the user.
*/
public function products()
{
return $this->hasManyThrough('AppProduct', 'AppCollection');
}
这将生成一个集合对象,其中包含用户的所有产品。