【问题标题】:What type of relationship these two tables will have in laravel?这两个表在 laravel 中会有什么样的关系?
【发布时间】:2014-05-13 05:28:07
【问题描述】:

我在数据库中有四个表:

  1. users(用于存储用户详细信息)
  2. 对话(用于存储对话 ID)。
  3. conversationsmember(用于存储会话成员)
  4. conversationsreply(用于存储对话回复)

一个用户会有很多对话,每个对话都有自己的成员和回复。

详情如下:

用户迁移:

$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();

现在在用户模型中,我需要定义用户表和对话表之间的关系。由于它们没有直接连接,因此我使用了 hasManyThrough 关系。

..app/models/User.php

...
    public function conversations()
        {
            return $this->hasManyThrough('Conversation', 'ConversationsMember', 'conversation_id', 'id');
        }
...

当我尝试使用它时,它显示一个空白数组。

【问题讨论】:

    标签: php laravel relationship


    【解决方案1】:

    我会尝试 belongsToMany 关系,其中 conversationsmembers 是您的数据透视表。

    public function conversations()
    {
        return $this->belongsToMany('Conversation', 'conversationsmembers');
    }
    

    您可能还想在对话模型中定义反向关系:

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

    我对你的迁移有点困惑,所以我不确定这就是你想要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 2012-05-20
      • 2019-11-14
      相关资源
      最近更新 更多