雄辩加入数据透视表?

时间:2014-12-16 00:29:28

标签: php laravel eloquent

我有一个名为message_recipients的数据透视表,看起来像

CREATE TABLE `message_recipients` (
  `user_id` bigint(20) unsigned NOT NULL,
  `message_id` bigint(20) unsigned NOT NULL,
  KEY `message_recipients_user_id_index` (`user_id`),
  KEY `message_recipients_message_id_index` (`message_id`),
  CONSTRAINT `message_recipients_message_id_foreign` FOREIGN KEY (`message_id`) REFERENCES `messages` (`id`),
  CONSTRAINT `message_recipients_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

然后我有一个messages

CREATE TABLE `messages` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `sender_id` bigint(20) unsigned NOT NULL,
  `subject` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `message` longtext COLLATE utf8_unicode_ci NOT NULL,
  `status` tinyint(4) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `messages_sender_id_index` (`sender_id`),
  CONSTRAINT `messages_sender_id_foreign` FOREIGN KEY (`sender_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=110 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

默认的user表。

我有以下课程

class MessageRecipients extends Eloquent {
    protected $table = 'message_recipients';
    public $timestamps = false;

    public function message() {
        return $this->hasMany('App\Models\Message');
    }

    public function user() {
        return $this->belongsTo('App\Models\User');
    }

    public function me() {
        return $this->belongsTo('App\Models\User');
    }
}

class Message extends Eloquent {
    public function recipients() {
        return $this->hasMany('App\Models\MessageRecipients');
    }

    public function sender() {
       return $this->belongsTo('App\Models\User');
    }
}

我正在试图弄清楚如何生成查询。我有

$message = Message::with('App\Models\MessageRecipients')->where('message_recipients.user_id', '=', 1)->first();

但我一直收到有关遗失message_recipients列的错误消息。如何生成看起来像(或生成相同数据)的查询

SELECT
 *
FROM
    messages
JOIN
    message_recipients
ON
    messages.id = message_recipients.message_id
WHERE
    message_recipients.user_id = 1

或者基本上选择分配给该用户的具有message_recipients数据的所有消息。

0 个答案:

没有答案