从2个不同的表中检索值,并将它们放在Laravel - foreach的视图中

时间:2013-12-22 19:58:05

标签: php join laravel eloquent

我正在使用Laravel框架。

我有2个表(用户和人员)。我想在表格中显示person_firstname,person_surname,user_username,user_email,user_created。

表用户

CREATE TABLE IF NOT EXISTS `festival_aid`.`users` (
  `user_id` BIGINT NOT NULL AUTO_INCREMENT,
  `user_username` VARCHAR(45) NOT NULL,
  `user_email` VARCHAR(45) NOT NULL,
  `user_password` CHAR(32) NOT NULL,
  `user_salt` CHAR(32) NOT NULL,
  `user_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `user_modified` TIMESTAMP NULL,
  `user_deleted` TIMESTAMP NULL,
  `user_lastlogin` TIMESTAMP NULL,
  `user_locked` TIMESTAMP NULL,
  `user_token` VARCHAR(128) NULL,
  `user_confirmed` TIMESTAMP NULL,
  PRIMARY KEY (`user_id`, `person_id`),
  UNIQUE INDEX `user_email_UNIQUE` (`user_email` ASC),
  INDEX `fk_users_persons1_idx` (`person_id` ASC),
  CONSTRAINT `fk_users_persons1`
    FOREIGN KEY (`person_id`)
    REFERENCES `festival_aid`.`persons` (`person_id`)
    ON DELETE CASCADE
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

表人

CREATE TABLE IF NOT EXISTS `festival_aid`.`persons` (
  `person_id` BIGINT NOT NULL AUTO_INCREMENT,
  `person_firstname` VARCHAR(45) NULL,
  `person_surname` VARCHAR(45) NULL,
  `person_created` TIMESTAMP NOT NULL,
  `person_modified` TIMESTAMP NULL,
  `person_deleted` TIMESTAMP NULL,
  PRIMARY KEY (`person_id`))
ENGINE = InnoDB;

索引操作

public function index()
    {
        $person = Person::all();
        $user = User::all();
        //$user = User::where($person_id == $user_id);

        return View::make('users.index')
            ->with('user', $user)
            ->with('person', $person);

        return View::make('users.index');
    }

用户迁移

Schema::table('users', function(Blueprint $table)
        {
        $table->increments('user_id');
            $table->string('user_email');
            $table->timestamp('user_created');
            $table->timestamp('user_modified');
            $table->timestamp('user_deleted');
            $table->timestamp('user_lastlogin');
            $table->timestamp('user_locked');

            $table->foreign('person_id')
                ->references('id')->on('persons')
                ->onDelete('cascade');
        });

人员迁移

public function up()
    {
        Schema::table('persons', function(Blueprint $table)
        {
            $table->increments('person_id');

            $table->string('person_firstname');
            $table->string('person_surname');
        });
    }

模型用户

class User extends Eloquent  {

    protected $primaryKey = 'user_id';

    public function persons()
    {
        return $this->hasOne('Person', 'foreign_key');
    }
}

模特人

class Person extends Eloquent {

    protected $table = 'persons';

    protected $primaryKey = 'person_id';

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

    public $timestamps = false;
}

用户视图

@foreach($user as $user=> $value)
   <tr>
      <td>{{ $value->user_id }}</td>
      <td>{{ $value->person_firstname }}</td>
      <td>{{ $value->person_surname }}</td>
      <td>{{ $value->user_username }}</td>
      <td>{{ $value->user_email }}</td>
      <td>{{ $value->user_created }}</td>
   </tr>
@endforeach

给我user_id,user_username,user_email,user_created。

@foreach($person as $person=> $value)
    <tr>
       <td>{{ $value->user_id }}</td>
       <td>{{ $value->person_firstname }}</td>
       <td>{{ $value->person_surname }}</td>
       <td>{{ $value->user_username }}</td>
       <td>{{ $value->user_email }}</td>
       <td>{{ $value->user_created }}</td>
    </tr>
 @endforeach

给我user_firstname,user_surname。

我想将这两者与PHP结合起来。

我在foreach中尝试了一个foreach但是对于每个user_username,user_email,user_created它从表中给了我所有person_firstname的person_surname。

有人知道如何使用框架laravel进行此操作吗?

3 个答案:

答案 0 :(得分:1)

看起来你正在使用Eloquent ORM。您可能需要查看defining relationshipsquerying them上的文档。

首先,您必须稍微调整模型类以正确定义这种一对一关系,因为您以相反的方式定义了关系并且未能指定正确的键列。您的模型类应如下所示:

模型类User

class User extends Eloquent  {
    protected $primaryKey = 'user_id';

    public function person() {
        return $this->belongsTo('Person', 'person_id', 'person_id');
    }
}

模型类Person

class Person extends Eloquent {
    protected $table = 'persons';
    protected $primaryKey = 'person_id';
    public $timestamps = false;

    public function user() {
        return $this->hasOne('User', 'person_id', 'person_id');
    }
}

然后您应该能够像这样访问Person中的属性:

$user = User::find(1);
$user->person()->person_firstname;

答案 1 :(得分:0)

您应该使用一个查询一次从两个表中检索数据,如下所示:

SELECT
  p.person_firstname,
  p.person_surname,
  u.user_username,
  u.user_email,
  u.user_created
FROM
  users AS u,
  persons AS p
WHERE
  u.person_id = p.person_id;

这会比在for循环中使用单独的查询提供更好的性能,而且也更容易。

此外,我不明白为什么你会为表的每一列添加前缀,实际上是表名。

编辑:使用Laravel,您可以根据Laravel documentation表达以下查询:

DB::table('users')
            ->join('persons', 'users.person_id', '=', 'persons.person_id')
            ->select(
                'persons.person_firstname',
                'persons.person_surname',
                'users.user_username',
                'users.user_email',
                'users.user_created'
            );

答案 2 :(得分:0)

SELECT
    p.person_firstname, p.person_surname, u.user_username, u.user_email, u.user_created
FROM
    persons p, users u
WHERE
    p.person_id = u.person_id

这将只获取您在单个查询中提到的信息。