Laravel 5.4与外键的多对多关系

时间:2017-05-17 09:20:38

标签: php mysql laravel-5.4

我正在为我的auct_lots_full模型使用名称为Lot.php的数据表,其中主键为lot_id,为了一切正常,我使用Sofa/Eloquence扩展名, Mappable。所以这是我的模特:

<?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);

    }
}

2 个答案:

答案 0 :(得分:1)

模型文件中有一个primaryKey变量,默认情况下为id

/** * The primary key for the model. * * @var string */ protected $primaryKey = 'id';

如果您在 Lot 模型文件中覆盖此变量。因此,您的主键将是lot_id,而不是默认的id。只需添加此内容;

protected $primaryKey = 'lot_id';

答案 1 :(得分:0)

所以实际上我找到了一个正确的方法来完成沙发/口才扩展,不仅使用外键而且还使用多对多关系中的本地密钥。所以这是新代码:

所以对于Lot.php我这样做了:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


class Lot extends Model
{

    protected $table = 'auct_lots_full';

    protected $primaryKey = 'lot_id';

    public function scopeFilter($query, QueryFilter $filters)
    {
        return $filters->apply($query);
    }

    public function comments()
    {
        return $this->hasMany(Comment::class,'lot_id', 'lot_id');
    }

}

我对于Comment.php模型做了同样的事情:

<?php

namespace App;


class Comment extends Model
{


    public function lot()
    {
        return $this->belongsTo(Lot::class, 'lot_id', 'lot_id');

    }

    public function User()
    {
        return $this->belongsTo(User::class);

    }
}

所以我们在上面看到的,在Lot.php模型中,函数注释我传递了foreignKey:auct_lots_full表中的'lot_id'和comments表中的localKey'lot_id'表示{{1表。在Comment.php模型中,wi做了相同的但是在不是localKey的情况下它是ownerKey。我很难解释所以我会附上一些图像来理解。

Lot.php enter image description here

Comment.php enter image description here