我收到错误"试图获取财产' company_name'非对象"。我研究了Eloquent关系并尝试在我的代码中实现。但它在视图(products.show)中给了我这个错误
哪部分错了?
与其他模特有很多不同的关系吗?
供应商模型':
public function getRouteKeyName()
{
return 'roc_no';
}
public function user()
{
return $this->belongsTo('App\User');
}
public function products()
{
return $this->hasMany('App\Product');
}
在'产品型号':
public function getRouteKeyName()
{
return 'slug';
}
public function user()
{
return $this->belongsTo('App\User');
}
public function vendor()
{
return $this->belongsTo('App\Vendor');
}
用户模型':
public function vendor()
{
return $this->hasOne('App\Vendor');
}
public function products()
{
return $this->hasMany('App\Product');
}
public function roles()
{
return $this->belongsToMany('App\Role', 'role_users');
}
在&products产品中显示':
...
{!! $product->description !!}
<!-- The error is at $product->vendor->company_name -->
Company Name: <a href="/vendors/{{ $product->vendor_roc_no }}">{{ $product->vendor->company_name }}</a>
&#39; ProductController&#39;:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|string|max:255',
'slug' => 'required|string|max:100',
'description' => 'required',
'image' => 'nullable',
]);
$product = new Product;
$product->name = $request->name;
$product->slug = $request->slug;
$product->description = $request->description;
$product->vendor_roc_no = auth()->user()->vendor->roc_no;
$product->save();
return redirect('/account/products')->with('success', 'Product added successfully.');
}
public function show(Product $product)
{
return view('products.show')->with('product', $product);
}
更新: 在供应商表中:
Schema::create('vendors', function (Blueprint $table) {
$table->increments('id');
$table->string('company_name');
$table->string('roc_no');
$table->string('company_address');
$table->string('company_tel');
$table->string('company_fax')->nullable();
$table->string('company_email');
$table->string('company_website')->nullable();
$table->string('company_logo')->nullable();
$table->text('company_profile')->nullable();
$table->unsignedInteger('user_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
在产品表中:
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug')->unique();
$table->text('description');
$table->string('image')->nullable();
$table->string('vendor_roc_no');
$table->timestamps();
// $table->foreign('vendor_id')->references('id')->on('vendors');
});
答案 0 :(得分:1)
据我所知,您需要建立从其他模型访问属性的关系,因此在这种情况下,您希望获取供应商上的company_name,您需要告诉您模型带来供应商。示例:
$user->with('anyRelation')->get();
// Then you can use like, $user->anyRelation->property;
现在我注意到你的show方法中有些东西,你发送的是Product类但不是一个雄辩的对象,可能只是使用Eloquent会有帮助吗?实施例
$products = Product:all(); // this would return every record on your db
return view('products.show')->with('products', $products);
我希望这有帮助:)