目的の結果が得られません。私は定義したユーザーコレクションモデルを取得しようとしています。割り当てられたIDをソートし、そのIDの製品を取得します。ループコレクション、配列作成、laravelでコレクションに参加
これをコントローラに戻すことはできません。私はちょうど私が戻ってほしいものを得るエコーは、私はそれをコレクションに追加することを好むだろうし、私は2つの配列を呼び出すよりもむしろ1つのコレクション(私が必要とするすべて)から呼び出すことができます。
//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ループを行い、$製品を得ることができるように刃にそれを渡します私はそれを$コレクションに追加したいと思いますが、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);
}
}
私はあなたが今それを見ることができると思いますので更新しました。 – m33bo
私は理解しているように、コレクションモデルを通じてユーザーに属するすべての製品を探していますか? – btl
はい、製品IDの場所の代わりに各製品をコレクションに追加したいと考えています – m33bo