我正在使用由nicolaslopezj https://github.com/nicolaslopezj/searchable搜索的包,并且我试图做一个属于的关系,但是我在使用它时遇到了一些麻烦。
protected $searchable = [
/**
* Columns and their priority in search results.
* Columns with higher values are more important.
* Columns with equal values have equal importance.
*
* @var array
*/
'columns' => [
'products.title' => 10,
'products.description' => 5,
],
'joins' => [
"brand" => ['products.brand_id', 'brands.id']
],
];
public function brand()
{
return $this->belongsTo(Brand::class);
}这里的问题是,当数据库表被称为“品牌”时,它试图获取数据库表“品牌”。但是,如果我将其更改为brands,我会得到一个与laravel的关系错误。所以我真的不知道该怎么做。文档也没有很好地解释它。希望能帮上忙,谢谢!
发布于 2020-08-08 18:18:14
考虑到注释中讨论的内容,原始问题的解决方案是更新Brand模型,方法是将protected $table变量设置为'brand',然后调整上面的变量以反映这一点。
这应该会解决你最初的关系错误问题,并保持代码的一致性,就像你在评论中提到的那样。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Brand extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'brand';
}默认情况下,Laravel将始终假定数据库表是模型名称的复数形式。因此,如果您的模型是单数的,那么您应该假设它期望数据库表是复数形式,除非如上所述显式设置!
按如下所示调整其他代码,以引用brand.id而不是brands.id
protected $searchable = [
/**
* Columns and their priority in search results.
* Columns with higher values are more important.
* Columns with equal values have equal importance.
*
* @var array
*/
'columns' => [
'products.title' => 10,
'products.description' => 5,
],
'joins' => [
"brand" => ['products.brand_id', 'brand.id']
],
];
public function brand()
{
return $this->belongsTo(Brand::class);
}https://stackoverflow.com/questions/63313477
复制相似问题