php - Laravel 5 使用具有许多关系的数据透视表

标签 php mysql laravel laravel-5 eloquent

我正在制作一个投票系统,我有两个表:

  • polls 表:具有那些字段 (id,question,created_at,updated_at)。

  • choices 表:具有那些字段 (id,poll_id,choice)。

还有一个名为 choice_poll 的数据透视表:具有这些字段(id,choice_id,poll_id,ip,name,phone, comment ,created_at,updated_at)

投票模型:

class Poll extends Model 
{

    protected $table = 'polls';
    protected $fillable = ['question'];
    public $timestamps = true;

    public function choices()
    {
      return $this->BelongsToMany('App\Choice')->withPivot('ip','name','phone','comment');
    }
}

选择模型:

class Choice extends Model 
{

    protected $table = 'choices';
    protected $fillable = ['poll_id','choice'];
    public $timestamps = false;

    public function poll()
    {
      return $this->belongsTo('App\Poll')->withPivot('ip','name','phone','comment');
    }
}

现在,当我尝试构建此查询时,它不会返回选择:

$poll->first()->choices()->get()

PS:与第一次投票相关的选项表中有很多选项。

最佳答案

在这种情况下你有 Many To Many 关系,所以尝试更改 belongsTo in :

public function poll()
{
    return $this->belongsTo('App\Poll')->withPivot('ip','name','phone','comment');
}

对于 belongsToMany,它将是:

public function poll()
{
    return $this->belongsToMany('App\Poll')->withPivot('ip','name','phone','comment');
}

注意 1: 您必须将 BelongsToMany 更改为 belongsToMany,注意 B 应该小写。

注意 2:您想要带有时间戳的数据透视表 create_at,updated_at 正如您在 OP 中提到的那样,因此您必须使用 withTimestamps();:

return $this->belongsToMany('App\Poll')
            ->withPivot('ip','name','phone','comment')
            ->withTimestamps();

//AND in the other side also

return $this->belongsToMany('App\Choice')
            ->withPivot('ip','name','phone','comment')
            ->withTimestamps();

希望这对您有所帮助。

关于php - Laravel 5 使用具有许多关系的数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38547060/

相关文章:

php - 无法在使用 Lavacharts 创建的 Laravel 5.1 中呈现折线图

php - 创建哈希以与 Oracle DBMS_UTILITY.get_hash_value 匹配

php - Javascript 确认框与 php

php - mysqli 获取记录

mysql - 如何将一个表的值插入到另一个表中

php - mysqli_num_rows 没有返回准确的结果

php - 确定变量的数量并自动使用正确数量的变量进行bind_param

php - 从单元测试运行时,Laravel Schema::create 忽略表前缀

php - 使用 laravel 比较两个数组

PHP 头文件问题