Phalcon查询构建器无法获取联接表数据

时间:2017-01-06 09:55:51

标签: phalcon

我有两张桌子' sanpham'和' danhmuc'。我使用phalcon查询构建器从2个表中获取数据。

$laytin = $this->modelsManager->createBuilder()
      ->from("sanpham")
      ->innerJoin('danhmuc','sanpham.danhmuc=danhmuc.sodanhmuc')
      ->where('sanpham.sosanpham = '.$id.'')
      ->getQuery()
      ->getSingleResult();
      $breadcrumbs = array('/' => Tool::getTranslation()->_('trangchu'),"/Loai-san-pham/".$laytin->tendep."/".$laytin->sodanhmuc => $laytin->tendanhmuc,'' => $laytin->tieudesanpham );

查询运行,但$ laytin-> tendep,$ laytin-> sodanhmuc,$ laytin-> tendanhmuc in' danhmuc'表格没有显示。 sanpham'中的每一栏都是如此。表(例如:$ laytin-> tieudesanpham)正确显示。

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容添加特定列:

$this->modelsManager->createBuilder()->columns('danhmuc.tend‌​ep, danhmuc.sodanhmuc')

使用此方法,您必须在输出中添加所需的每列。 QueryBuilder docs。 另一种方法是查询Sanpham模型。

例如:

class Sanpham extends \Phalcon\Mvc\Model
{
    public static function findSomething($something)
    {
        // this is your actual query, it replaces the queryBuilder
        return self::query()
            ->where('sanpham.sosanpham = :id:', ['id' => $something])
            ->innerJoin('danhmuc', 'sanpham.danhmuc = danhmuc.sodanhmuc')
            ->execute()->getFirst();
    }

    public function initialize()
    {
        // define the relation to danhmuc
        $this->belongsTo('danhmuc', 'danhmuc', 'sodanhmuc');
    }
}

class Danhmuc extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        // there are other options besides "hasMany", like "hasOne".
        // this is your relation to sanpham
        $this->hasMany('sodanhmuc', 'sanpham', 'danhmuc');
    }
}

class YourController extends \Phalcon\Mvc\Controller
{
    public function testAction()
    {
        // get your first record in Sanpham matching "12345"
        $sanpham = Sanpham::findSomething(12345);

        // from your Sanpham object, get the related danhmuc object.
        // this works because we defined the relations (belongsTo and hasMany)
        $danhmuc = $sanpham->getRelated('danhmuc');

        // now you have access to the values of danhmuc via the $danhmuc variable
        $breadcrumbs = [
            '/'                                  => Tool::getTranslation()->_('trangchu'),
            "/Loai-san-pham/" . $danhmuc->tendep => $danhmuc->tendanhmuc,
            ''                                   => $danhmuc->tieudesanpham,
        ];
    }
}

检查Phalcon model docs以获取更多相关信息。