我正在为我的 Lot.php
模型使用名为 auct_lots_full
的数据表,其中主键为 lot_id
,以便排列所有内容上类时我用了 Sofa/Eloquence扩展名,可映射
。这是我的模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Sofa\Eloquence\Eloquence;
use Sofa\Eloquence\Mappable;
class Lot extends Model
{
use Eloquence, Mappable;
protected $table = 'auct_lots_full';
protected $maps =[
'id' => 'lot_id',
];
public function scopeFilter($query, QueryFilter $filters)
{
return $filters->apply($query);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
但问题是,在某些情况下,它会不断寻找 id
列作为主键。例如,在 LotsController.php
中我遇到了这个问题:
public function show($id)
{
$lot = Lot::find($id);
return view('lots.show')->withLot($lot);
}
但是我用这个解决方案解决了这个问题:
public function show($id)
{
$lot = Lot::where('lot_id', $id)->first();
return view('lots.show')->withLot($lot);
}
但我知道这只是此功能的解决方案......
所以我在 CommentsController.php
中遇到同样的问题:
public function show()
{
$comments = Comment::orderBy('id', 'desc')->paginate(30);
return view('comments.browse', compact('comments'));
}
而且我不知道如何解决它。谁能解释一下为什么会发生这种情况?有比使用扩展更好的方法吗?我如何修复 CommentsCotroller.php
中的此错误?
这是Comment.php
模型:
<?php
namespace App;
class Comment extends Model
{
public function lot()
{
return $this->belongsTo(Lot::class);
}
public function User()
{
return $this->belongsTo(User::class);
}
}
最佳答案
模型文件中有一个 primaryKey
变量,默认为 id
。
/**
* 模型的主键。
*
* @var 字符串
*/
protected $primaryKey = 'id';
如果您在Lot模型文件中覆盖此变量。因此,您的主键将是 lot_id
而不是默认的 id
。只需添加此即可;
protected $primaryKey = 'lot_id';
关于php - Laravel 5.4 与外键的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44020613/