我不知道出了什么问题。检查2个用户是否是laravel的朋友

时间:2013-06-16 11:04:40

标签: database model laravel friend

我是使用mvc框架的新手。我目前正在学习Laravel而且我被困住了。如果两个用户是朋友,我需要进行模型检查。

我有以下数据库:

   CREATE TABLE `users` (
     `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
     `firstname` varchar(30) NOT NULL,
     PRIMARY KEY (`id`)
   );

   INSERT INTO `users` (`id`, `firstname`) VALUES
   (1, 'name1'),
   (2, 'name2'),
   (3, 'name3'),
   (4, 'name4');

   CREATE TABLE `friends` (
     `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
     `user_id_from` int(10) unsigned NOT NULL,
     `user_id_to` int(10) unsigned NOT NULL,
     `status` enum('pending','accepted','blocked') NOT NULL,
     PRIMARY KEY (`id`),
     KEY `user_id_from` (`user_id_from`),
     KEY `user_id_to` (`user_id_to`)
   );

   INSERT INTO `friends` (`id`, `user_id_from`, `user_id_to`, `status`) VALUES
   (1, 1, 3, 'accepted'),
   (2, 1, 2, 'pending'),
   (3, 4, 1, 'pending'),
   (4, 4, 2, 'pending'),
   (5, 3, 4, 'accepted');

我的模特朋友看起来像这样:

    class Friend extends Eloquent 
    {
    public $user_id;
    public $user_id_from;
    public $friends;
    public $friend_user_id;

    public function check_friend($user_id, $friend_user_id){

    $this->user_id = $user_id;
    $this->friend_user_id = $friend_user_id;
    $this->friends =  DB::select('
            SELECT
                fu.id AS `friend_uid`
            FROM
                `users` AS `us`
            LEFT JOIN
                `friends` AS `fr`
            ON
                (fr.user_id_from = us.id OR fr.user_id_to = us.id)
            LEFT JOIN
                `users` AS `fu`
            ON
                (fu.id = fr.user_id_from OR fu.id = fr.user_id_to)
            WHERE
                fu.id != us.id
            AND
                fr.status = "accepted"
            AND
                us.id = ?', array($this->user_id));
    return in_array($this->friend_user_id, $q);
}
}

控制器:

    public function get_checkfriend(){
    $friend = new Friend;
    return $friend->check_friend(1,2);
}

我收到以下错误:in_array()期望参数2是数组,给定对象。 我转储了第二个参数(应该是我的查询结果),但里面有一个完全不同的东西(不是数据库中的数据)。

问题是我不知道我做错了什么。请帮忙

1 个答案:

答案 0 :(得分:1)

首先,由于您使用的是Laravel,因此您应该使用其内置的数据库功能。使用“架构”构建器生成数据库:http://laravel.com/docs/schema

其次,利用Eloquent的内置数据库关系功能:http://laravel.com/docs/eloquent#many-to-many

您的案例的快速示例将是这样的(我认为):

// app/models/user.php
class User extends Eloquent
{
    public function friends() {
        return $this->belongsToMany('User', 'friends', 'user_id', 'friend_id');
    }
}

// app/database/schema/user.php
Schema::create('users', function($table)
{
    $table->increments('id');
    $table->string('name');
    // and any other stuff you want in your user database
});

// app/database/schema/friend.php
Schema::create('friends', function($table)
{
    $table->increments('id');
    $table->integer('user_id');
    $table->integer('friend_id');
});