We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

how to use hasone

i have two myISAM tables:ex1 ex2. each table have two Field.They are id1,t1(ex1) ; id2,t2(ex2); how to use hasone method that it can be the same as this SQL:

select ex1.*,ex2.* from ex1 inner join ex2 where ex1.id1=ex2.id2;

model:

//model ex1.php
namespace Frontend\Model;       
class ex1 extends \Phalcon\Mvc\Model{    
    public initialize(){
        $this->hasone( 'id1' , 'Model\ex2' , 'id2' , array( 'alias' => ‘ex2’) );
    }
}

controller:

//controller indexController.php     
namespace  Frontend\Controller; 
use \Frontend\Model\ex1;

class indexController extends Phalcon\Mvc\Controller{     
    public indexAction(){
        $result = ex1::find() -> toArray();
        var_dump( $result );
    }
}

OS: win8.1 64 Nginx:1.8.1 PHP:php-5.4.45-nts-Win32-VC9-x86 Phalcon:2.1.0r

The result is : only ex1 data can be displayed. how to fix it? Thanks for your help.

Change it to belongsTo



705

I've tried. But the results did not change.

Change it to belongsTo



145.0k
Accepted
answer

But you didn't even accesed data ? You need to make a join men. Use queryBuilder or ::query static method



705

i use raw sql to solve:

static public function queryAll()
    {
        # code...
        $sql = 'SELECT tdm_ex1.* ,tdm_ex2.* FROM tdm_ex1 INNER JOIN tdm_ex2 WHERE tdm_ex1.id1=tdm_ex2.id2';

        $ex1= new self();

        return new Resultset( null , $ex1 , 
            $ex1 ->getReadConnection() -> query($sql)
        );
    }

But you didn't even accesed data ? You need to make a join men. Use queryBuilder or ::query static method



705

Thanks,it works.

CreateBuilder:

$result = $modelsManager -> createBuilder()
            ->columns('Ex1Model.*,Ex2Model.*')          
            ->from( ['Ex1Model' => 'Tdm\Home\Models\Ex1Model'] )
            ->join( 'Tdm\Home\Models\Ex2Model', 'Ex1Model.id1 = Ex2Model.id2' , 'Ex2Model' ,'INNER' )           
            ->getQuery()
            ->execute();

PHQL:

$result=$modelsManager ->executeQuery( '
            select Ex1Model.id1,Ex2Model.id2 from Tdm\Home\Models\Ex1Model as Ex1Model 
            inner join Tdm\Home\Models\Ex2Model as Ex2Model on Ex1Model.id1 =Ex2Model.id2           
        ');

You can use phalcon ::query or models manager. No need to use raw sql, https://docs.phalcon.io/pl/latest/reference/phql.html#creating-queries-using-the-query-builder