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

Model relationship query vs query builder join

Hello, What is a better one to query data and related record in another table between get model and select related record when use or join table using query builder.

I have 2 tables Property and Property image, which method is better to show a property.

## property model ##
class Property extends \Phalcon\Mvc\Model
{
/**
 * @Primary
 * @var integer
 */
public $id;

/**
 * @var string
 */
public $name;

  /**
 * @var string
 */
public $slug;

public function initialize()
{
$this->hasMany("id", "Property_image", "property_id", array('alias' => 'Image'));
}
}

## property_image ##
class Property_image extends \Phalcon\Mvc\Model
{
    /**
 * @Primary
 * @var integer
 */
public $id;

 /**
 * @var string
 */
public $property_id;

/**
 * @var string
 */
public $image;

public function initialize()
{
        $this->belongsTo("property_id", "Property", "id", array('alias' => 'Property'));
}
}

Method 1:

    $property = Property::findFirstBySlug($slug);
    $images = $property->Image;
    foreach ($images as image) { echo $image->image;}

Method 2:

    $property = $this->modelsManager->createBuilder()
    ->columns('PI.image'))
    ->addfrom("Webapp\Frontend\Models\Property","P")
    ->leftjoin("Webapp\Frontend\Models\Property_image","PI.project_id = P.id","PI")
    ->where("P.slug = :slug:",array("slug" => $slug))
    ->getQuery()
    ->execute()
    ->getFirst();

another question, If use method 2 and I want to update property table, Do I have to find fiest by slug again and use $property->save() ?

In method 1 you make 2 request in to DB. In method 2 it should be only one request.

maybe you can use third method in this case. Something like this:

$property_image = Property_image::findByPorpertyId($slug);
foreach ($property_image as $image) { 
    echo $image->image;
}

Your question to update i cant answer, becouse dont understand what you exactly mean. But in case you wont to update record in database, you can use $property->update(), instead of $property->save(). Its faster. And you dont create new record instead updating one, if you miss id or something go wrong.