【发布时间】:2014-05-12 08:21:16
【问题描述】:
我正在使用 laravel 创建一个消息传递应用程序。我使用了四个迁移(用户、对话、对话成员和对话回复)。我还定义了模型之间的关系。
用户的详细信息将存储在用户表中。对话 ID 将存储在对话表中。每个对话都会有成员。成员的详细信息将存储在会话成员表中,最后回复将存储在会话回复表中。
现在我试图显示特定用户的所有对话(我在 User 和 ConversationMembers 模型之间使用了 hasManyThrough 关系),但它不起作用。
详情如下:
用户迁移:
$table->increments('id');
$table->string('name', 32);
$table->string('username', 32);
$table->string('email', 320);
$table->string('password', 64);
$table->timestamps();
对话迁移:
$table->increments('id');
$table->timestamps();
conversationsmembers 迁移:
$table->increments('id');
$table->integer('conversation_id');
$table->integer('user_id');
$table->timestamps();
对话回复迁移
$table->increments('id');
$table->integer('conversation_id');
$table->integer('user_id');
$table->timestamps();
用户模型: 我已将这些方法添加到默认用户模型中
public function conversations()
{
return $this->hasManyThrough('Conversation', 'ConversationsMember', 'conversation_id', 'id');
}
public function conversationsMember(){
return $this->hasMany('ConversationsMember', 'user_id', 'id');
}
public function conversationsReply(){
return $this->hasMany('ConversationsReply', 'user_id', 'id');
}
对话模型
class Conversation extends Eloquent{
public function conversationsMember(){
return $this->hasMany('ConversationsMember', 'conversation_id', 'id');
}
public function conversationsReply(){
return $this->hasMany('ConversationReply');
}
}
ConversationsMember 模型
class ConversationsMember extends Eloquent{
protected $fillable = array('conversation_id', 'user_id');
protected $table = 'conversationsmember';
public function users(){
return $this->belongsTo('User', 'user_id', 'id');
}
public function conversations(){
return $this->belongsTo('Conversation', 'conversation_id', 'id');
}
}
对话回复模型
class ConversationsReply extends Eloquent{
protected $fillable = array('reply', 'user_id','conversation_id', 'ip');
protected $table = 'conversationsreply';
public function users(){
return $this->belongsTo('User', 'user_id', 'id');
}
public function conversations(){
return $this->belongsTo('Conversation', 'conversation_id', 'id');
}
}
【问题讨论】:
-
可能值得解释一下“不工作”的含义。错误?没有结果?奇怪的结果?
-
当我通过用户模型调用对话方法时,什么都没有发生。我使用 print_r 查看结果,它显示了两个大括号()
-
好吧,看看你的架构和代码,你似乎要么错误地使用了
hasManyThrough,要么错误地建模了你的数据。据我了解,hasManyThrough在X有很多Y时使用,然后Y有很多Z并且您想为给定的X获取所有Zs。因此,您的架构需要在Y上拥有x_id,在Z上拥有y_id。如果这不是您要查找的内容,但实际上X有很多Y并且Y有很多X,那么您需要belongsToMany而不是hasManyThrough。根据您的架构(您有一个数据透视表),后者似乎是您想要的。也许试试看。 -
对于表格和列的拼写(和复数形式),请务必关注the conventions。
-
@alexrussell,我认为是 X hasOne Y,Y hasMany Z。检查这个其他答案stackoverflow.com/questions/22720311/…
标签: php laravel relationship eloquent