Orm 使用单表的拉维关系

Orm 使用单表的拉维关系,orm,laravel,laravel-4,eloquent,Orm,Laravel,Laravel 4,Eloquent,我有一个带有此迁移模式的表 Schema::create('pages', function(Blueprint $table) { $table->integer('id', true); $table->string('title'); $table->string('slug'); $table->string('layout'); $table->text('body'); $table->integer('pare

我有一个带有此迁移模式的表

Schema::create('pages', function(Blueprint $table) {
   $table->integer('id', true);
   $table->string('title');
   $table->string('slug');
   $table->string('layout');
   $table->text('body');
   $table->integer('parent_id');
   $table->integer('page_order');
   $table->enum('is_navigation', array('yes', 'no'))->default('yes');
   $table->timestamps();
   $table->softDeletes();
});
此表用于保存动态多级页面详细信息。如果该页面是父页面,
parent\u id
将为零,如果一个页面位于另一个页面下,则该页面的父页面id将为
parent\u id
。现在,我需要在包含父标题的表中显示数据。我的密码是

$table_prefix = DB::getTablePrefix();

$pages = DB::select(DB::raw("select A.*,B.title as parent from ".$table_prefix."pages as A left join ".$table_prefix."pages as B on A.parent_id = B.id where A.deleted_at is null"));
它工作正常,但我不能在这里使用
paginate()

如何使用雄辩的关系替换此查询。

您可以在那里使用
paginate()
。请看下面的图片

您还可以使用雄辩的方式删除废弃的where子句,因为雄辩应该处理这个问题

Page::where("pages.*", "parent_pages.title as parent")
    ->leftJoin('pages as parent_pages', 'parent_pages.id = pages.parent_id')
    ->paginate(10);

没有测试,只是重新分解原始查询字符串

这是正确的ORM方法。首先在模型中定义关系。然后在查询过程中加载关系。使用eager加载时,这会在两个SQL查询中发生。一个用于页面列表,另一个用于所有页面

// In Page class

public function parent()
{
    return $this->belongsTo('Page', 'parent_id');
}

// Elsewhere

$pages = Page::with('parent')->paginate(10);

foreach ($pages as $page)
{
    if ($page->parent)
    {
        echo $page->parent->title;
    }

    echo $page->title;
}

这些查询给了我这个错误
SQLSTATE[42000]:语法错误或访问冲突:1064您的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以了解在“
附近使用的正确语法,其中
页面
处的
已删除\u
为空,并且第1行的
页面
*=?”(SQL:select count()作为来自
页面的聚合
左连接
页面
作为
cmsplus\u父页面上的
父页面
id=pages
父页面id
,`where
页面
处删除的
页面为空且
页面
?)(绑定:数组(0=>'parent\u pages.title as parent')``尝试显式定义SQL列,这并不是最终的解决方案。只是让你知道你实际上可以在你认为不可能的地方使用
paginate()
。现在我得到了
结果:{}
with
public function index(){$pages=Page::with('parent')->paginate($limit=10);返回Response::json(array('status'=>'success','message'=>'Page successfully loaded!','results'=>$pages),200);}
隔离问题。如果添加($results),会发生什么?DB实际返回什么?如果改用->get()会发生什么?
// In Page class

public function parent()
{
    return $this->belongsTo('Page', 'parent_id');
}

// Elsewhere

$pages = Page::with('parent')->paginate(10);

foreach ($pages as $page)
{
    if ($page->parent)
    {
        echo $page->parent->title;
    }

    echo $page->title;
}