我正在有效地尝试定义用户(发送者和接收者)与消息之间的关系。
“我的消息”迁移是:
<?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/