arrays之Laravel之从数据库 View 中显示数组/字符串对象

mate10pro 阅读:55 2024-12-31 21:38:35 评论:0

数据存储为 ["item_1", "item_2"]在如下所示的数据库中。
我想在 View Blade 中正确显示这些数据。

产品型号

protected $fillable = ['name', 'prod_id']; 
public function models() { 
    return $this->hasMany(Model::class, 'prod_id'); 
} 
型号 型号
protected $fillable = ['model', 'prod_id']; 
protected $cat = ['model'=>'array']; 
public function model() 
{ 
 return $this->belongsTo(Product::class, 'prod_id'); 
} 
Controller - 存储方法
public function create (Request $request, Product $product){ 
$models = new Model; 
    { 
     $model = json_encode(request('models')); 
     $items->models = $model; 
     $product->models()->save($models); 
    } 
} 
Controller 显示方法
public function show(request $id){ 
 $product = Product::findorfail($id); 
 $models = Model::with(['model'])->where('prod_id', $product->id)->get(); 
 return  view ('show',  compact('product', 'models')); 
创建 View
<input type="checkbox" name="model[]" value="Samsung"> 
<input type="checkbox" name="model[]" value="Nokia"> 
<input type="checkbox" name="model[]" value="Apple"> 
<button>Add Model</button> 
我试过显示 View :
@foreach($models as $model) 
  {{ json_decode($model->models) }} 
@endforeach 
它抛出

htmlspecialchars() expects parameter 1 to be string, array given


我错过了什么。
PS:MySQL不支持json列,所以我保存为文本列。

请您参考如下方法:

你需要做这样的事情。

型号 型号

protected $fillable = ['models', 'prod_id']; // screenshot says that the field name is "models" 
 
protected $cast = ['models' => 'array']; // the property is $cast no $cat   
 
public function product() 
{ 
 return $this->belongsTo(Product::class, 'prod_id'); 
} 

ModelController - 存储方法
public function store (Request $request){   
 
  $product = Model::create([ 
    'models' => json_encode($request->models), 
    'prod_id' => $request->prod_id 
  ]);   
 
  return redirect()->back()->with('success', 'created!'); 
} 
 
public function show(Request $id){ 
 
  $model = Model::findOrFail($id)->with('product'); 
 
  return  view ('model.show',  compact('model')); 
} 

ProductController 显示方法
public function show(request $id){ 
 $product = Product::findOrFail($id)->with('models'); // the method name is findOrFail() no findorfail  
 // $models = Model::with(['model'])->where('prod_id', $product->id)->get(); 
 return  view ('show',  compact('product')); 
} 

进入展会查看
@foreach($product->models as $models) 
  @foreach(json_decode($models->models) as $model) 
    {{ $model }} 
  @endforeach 
@endforeach 


标签:数据库
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号