【发布时间】:2018-05-21 15:20:00
【问题描述】:
我收到错误“尝试获取非对象的属性 '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.show”中:
...
{!! $product->description !!}
<!-- The error is at $product->vendor->company_name -->
Company Name: <a href="/vendors/{{ $product->vendor_roc_no }}">{{ $product->vendor->company_name }}</a>
在“产品控制器”中:
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');
});
【问题讨论】:
-
似乎您至少有一个供应商没有与之关联的供应商。在尝试使用之前,您应该检查供应商是否存在。如果您使用的是 Laravel 5.5+,您可能会发现 optional() 函数很方便。
-
什么意思?抱歉,我还是新手,对 Laravel 和框架的经验较少。我认为关系定义是正确的,对吧?哦,当我使用辅助函数 optional() 时,它返回 null 而不是错误。
-
我认为不是,但不看表格很难说。试试这个:
return $this->belongsTo('App\Vendor', 'vendor_roc_no'); -
@devk 仍然无法正常工作。我已经更新了问题。
-
试试
return $this->belongsTo('App\Vendor', 'vendor_roc_no', 'roc_no');。
标签: php laravel laravel-5 eloquent