Magento 2 Left Join 资源模型类中的 SQL 查询以从多个表中获取数据。
Left Join 用于从左表中获取所有记录并从第二个表中检索匹配的记录。
我们可以使用joinLeft()方法在 Magento Collection 中使用 Left Join。
一个演示,使用连接查询从customer_address_entity表中获取具有客户地址详细信息(如城市和邮政编码)的客户。
joinLeft() 的定义:
joinLeft($name, $cond, $cols = '*', $schema = null)
这里参数数据类型,
* $name will be array|string|Zend_Db_Expr
* $cond string Join condition with other tables.
* $cols will be array|string. Columns to select from the joined table.
* $schema string. The database name to specify if any.
<?php declare(strict_types=1);
/**
* Model Class
*
* @author Rakesh Jesadiya <rakesh@jesadiya.com>
* @package Rbj_OrderTotal
*/
namespace Rbj\OrderTotal\Model;
use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory;
use Magento\Framework\App\ResourceConnection;
class General
{
/**
* @var CollectionFactory
*/
private $customerRepository;
public function __construct(
CollectionFactory $customerCollectionFactory,
ResourceConnection $resource
) {
$this->customerCollectionFactory = $customerCollectionFactory;
$this->resource = $resource;
}
public function getCustomerData()
{
$customerCollection = $this->customerCollectionFactory->create();
$customerCollection->addAttributeToFilter('email', 'rakesh@jesadiya.com');
$customerCollection->getSelect()->joinLeft(
['ca' => $this->getTable('customer_address_entity')],
'e.entity_id = ca.parent_id',
['city', 'postcode']
);
return $customerCollection->getData();
}
public function getTable(string $name) {
return $this->resource->getTableName($name);
}
}
您也可以在多个表上编写连接操作。SQL Query 不仅限于两个表关系。
您可以在单个查询中在表之间进行多个连接。
连接查询的一些简要说明,
$customerCollection将customer_entity表指示为主表。
$customerCollection->getSelect()->joinLeft(
['ca' => $this->getTable('customer_address_entity')],
'e.entity_id = ca.parent_id',
['ca.city', 'ca.postcode ']
);
第一个 参数是要加入的表名,ca是customer_address_entity的别名。
第二个参数是加入其他表的条件。//'e.entity_id = ca.parent_id'
第三个参数是第二个(Join)表所需的列列表。