我可以使用laravel 4 eloquent模型,还是需要使用db:query

时间:2014-09-23 02:29:28

标签: laravel eloquent query-builder

您好我正在尝试将第一次尝试与Laravel一起使用ORM。我有一个Drupal的大表,我想要获取一些记录,我需要加入Drupal中的另一个表来获取我关心操作的记录。 像这样......

Node
----------------------------------------------------------
| Nid | type       | misc other stuff | N
==========================================================
| 1  | Programs    | Test Service    | 1       |
----------------------------------------------------------
| 2  | Programs    | Example Service | 1       |
----------------------------------------------------------
| 3  | Something else   | Another Service | 1       |
----------------------------------------------------------

Fields
----------------------------------------------------------
| id | title                         | NID | tag     |
==========================================================
| 1  | Blog Title 1                  | 1       | THER    |
----------------------------------------------------------
| 2  | Blog Title 2                  | 2       | TES     |
----------------------------------------------------------
| 3  | Blog Title 3                  | 3       | ANOTHER |
----------------------------------------------------------

我希望获得所有类型='程序'和内部连接那些与NID相同的所有领域。我是否在app / model / node.php中使用Eloquent ORM执行此操作?或者查询构建器语句$ model = DB:table?这是什么代码?或者我只是用PHP做到这一点?

3 个答案:

答案 0 :(得分:0)

我更喜欢查询构建器,它更灵活

DB::table('Node')
->join('Fields', 'Fields.NID', '=', 'Node.Nid')
->where('type', 'Programs')
->get();

答案 1 :(得分:0)

您可以使用ORM执行此操作,但必须覆盖使其变得方便和优雅的所有内容。

因为你说你正试图操纵"在fields表中的数据,听起来你正在尝试使用Drupal字段系统之外的其他东西来更新Drupal表。我一般不建议这样做 - Drupal现场系统很大,很复杂,也很特别。整个CMS都可以使用它。

您应该使用种子(http://laravel.com/docs/4.2/migrations#database-seeding)将数据移出旧的Drupal数据库并移入新数据库。

定义一个" drupal" app / config / database.php中的数据库连接,以及您作为"默认"使用的任何内容。连接新应用程序。您可以通过以下方式从备用连接中获取Eloquent模型:

<?php

// $nodes is an array of node table records inner joined to fields
$nodes = DB::connection('drupal')
    ->table('node')
    ->join('fields', 'node.nid', '=', 'fields.nid')
    ->get();

将数据拉出并使用Laravel迁移到适当的表中,将其放入规范化的ActiveRecord样式表(http://laravel.com/docs/4.2/migrations#creating-migrations)。

答案 2 :(得分:0)

在app / model(node.php和field.php)中创建两个模型,如下所示:

class Node extends \Eloquent {
    protected $fillable = [];
    protected $table = 'Node';

    public function fields()
    {
        return $this->hasMany('Field');
    }
}

class Field extends \Eloquent {
    protected $fillable = [];

    public function node()
    {
        return $this->belongsTo('Node');
    }
}

你可以做这样的事情:

$nodes = Node::with('fields')->where('type', 'Programs')->get();

您将获得所有节点的关系,其类型为“程序”。

相关问题