Laravel:如何从数据透视表中获取记录,其外键不引用主键?

时间:2014-07-19 04:26:13

标签: php mysql laravel laravel-4 eloquent

我有两个由belongsToMany关系链接的表和一个数据透视表,它工作正常。然后我尝试在数据透视表中引用非主键而不是主键。但是,当我在控制器中运行代码时,laravel不会返回任何结果。

我想这可能是因为在belongsToMany关系中,laravel会自动认为数据透视表中的外键引用了主键,这就是我的代码无效的原因。

如何更改laravel的逻辑?

P.S。我可以通过使用ConversationsUser模型获取这些记录,但它访问数据库两次以获得结果(它首先检查会话表,然后检查数据透视表)。如果我找不到其他解决方案,这将是我的最后手段。


CONTROLLER

$loginuser = User::find(Auth::user()->id);
$conversations = $loginuser->conversations;
dd($conversations->toArray());

当数据透视表中实际存在有效记录时,它返回一个空数组。我需要它来返回那些记录。

模型

用户

public function conversations(){
   return $this->belongsToMany('Conversations')->withPivot('opened','last_seen');
}

对话注意:正如您所看到的,我已尝试添加另外两个参数suggested in this answer,但仍然无效。

public function users(){
    return $this->belongsToMany('User','conversations','conversations_id');
}

MIGRATIONS

用户

Schema::create('users',function($table)
        {
            $table->increments('id');
            $table->string('email')->unique();
            $table->string('password',100);
            $table->string('name',150);
            $table->string('usertype',50);
            $table->boolean('block');
            $table->string('remember_token',100);
            $table->timestamp('lastlogin_at');
            $table->timestamps();
            $table->softDeletes();
        });

会话

        Schema::create('Conversations', function(Blueprint $table)
        {
            $table->increments('id');
            $table->bigInteger('conversations_id')->unsigned()->index();
            $table->string('name',100);
            $table->timestamps();
            $table->bigInteger('microseconds');
        });

conversations_user

        Schema::create('conversations_user', function(Blueprint $table)
        {
            $table->increments('id')->unsigned();
            $table->bigInteger('conversations_id')->unsigned()->index();
            $table->foreign('conversations_id')->references('conversations_id')->on('conversations')->onDelete('cascade');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
            $table->bigInteger('microseconds');
            $table->boolean('opened');
            $table->dateTime('last_seen');
        });

1 个答案:

答案 0 :(得分:1)

尝试从此更改

public function users(){
    return $this->belongsToMany('User','conversations','conversations_id');
}

到这个

public function users(){
    return $this->belongsToMany('User','conversations_user','user_id','conversations_id');
}

belongsToMany的第二个参数是根据[0]

的联结表的表名

[0] http://laravel.com/api/class-Illuminate.Database.Eloquent.Relations.BelongsToMany.html

另外,因为您在Conversations表中使用了不同的键,尝试在模型类中添加这两个变量,在Conversation模型中更改它:

class Conversation extends Eloquent {
    protected $primaryKey = "conversation_id";
    public $incrementing = false;