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() ?