简体   繁体   中英

How do I select specific columns on table join in propel?

I need to select specific set of columns from both the table using propel orm 2.0.0. The equivalent query is as below

select b.name as brand_name, b.grade, d.name as dealer_name, d.number
from brand as b join dealer as d
on d.id = b.dealer_id;

I am struggling where the necessary columns on both the tables have same name but need to join using different column.

Help me with the propel php code and also with proper reference site. The document at official site is not a good tutorial.

This should work, provided you have correctly defined your models.

$rows = BrandQuery::create()
    ->select(['name', 'grade'])
    ->joinWith('dealer')
    ->withColumn('dealer.name', 'dealer_name')
    ->withColumn('dealer.number')
    ->find();

You need to use ORM. Assuming all models properly setup:

<?php
$brands = BrandQuery::create()->find();
// $brands contains a collection of Brand objects
// one object for every row of the brand table
foreach($brands as $brand) {
    $dealers = $brand->getDealers();
    // $dealers contains a collection of Dealer objects for this brand
    // one object for every row of the dealers table for brand row
}

Another (and I think better) way here would be using custom SQL.

<?php
use Propel\Runtime\Propel;
$con = Propel::getWriteConnection(YOUR_DATABASE_NAME);
$sql = "select b.name as brand_name, b.grade, d.name as dealer_name, d.number from brand as b join dealer as d on d.id = b.dealer_id";
$stmt = $con->prepare($sql);
$stmt->execute();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM