orm - 请解释 Laravel ORM 中的foreign_key 和 local_key 关系

标签 orm laravel-4

我正在有效地尝试定义用户(发送者和接收者)与消息之间的关系。

“我的消息”迁移是:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateMessagesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
        Schema::create('messages', function($t){
            $t->increments('id');
            $t->integer('sender_user_id')->unsigned();
            $t->integer('recipient_user_id')->unsigned();
            $t->string('subject');
            $t->text('content');
            $t->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
        Schema::dropIfExists('messages');
    }

}

我的消息模型很简单:

<?php

class Message extends Eloquent{
    // link to sender user id
    public function from(){
        return $this->hasOne('User', 'sender_user_id'); 
    }
    // link to recipient user id
    public function to(){
        return $this->hasOne('User', 'recipient_user_id');
    }
}

但我不确定在我的用户模型中定义 hasMany 关系。

文档 ( http://laravel.com/docs/eloquent#relationships ) 显示以下内容:

return $this->hasMany('Comment', 'foreign_key');

return $this->hasMany('Comment', 'foreign_key', 'local_key');

现在,我很困惑后一个 hasMany 关系中哪个键是哪个。哪个对于我的用户模型是正确的?

public function sentMessages(){
    return $this->hasMany('Messages', 'id', 'sender_user_id');
}

public function sentMessages(){
    return $this->hasMany('Messages', 'sender_user_id', 'id');
}

最佳答案

您必须像这样设置关系:

public function sentMessages()
{
    return $this->hasMany('Messages', 'sender_user_id');
}

public function receivedMessages()
{
    return $this->hasMany('Messages', 'recipient_user_id');
}

关于orm - 请解释 Laravel ORM 中的foreign_key 和 local_key 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22504928/

相关文章:

java - 如何在 Hibernate 中映射一组枚举类型?

javascript - Laravel 字符串本地化和 AngularJS

php - Laravel - 从自定义类重定向

jquery - BlueImp 文件上传 "Error: Method Not Allowed"- Laravel 4 路由问题

mysql - 在 Laravel Query Builder 中合并来自不同数据库的查询

php - 在编辑模式下使用 Laravel 数组表单复选框

java - 多对多关联。数据不删除

java - "Select or create"来自数据库,在 Java 中

nhibernate - Entity Framework 成功案例?

java - 如何使用JPA从自引用实体中的某个级别选择子实体?