我的 Laravel 5 项目中有 3 个表:输出、产品和服务。
我想根据此条件将这 3 个表加入到一个查询中:
if outputs.article_type = 'p'
(p = 产品)获取 products.name
if outputs.article_type = 's'
(s = service) 获取 service.name
$outputs = Output::join('products', 'products.id', '=', 'outputs.article_id')
... only if outputs.article_type is p (p=product)
->join('services', 'services.id', '=', 'outputs.article_id')
... only if outputs.article_type is s (s=service)
->select(array('outputs.output_at','---services or product---.name as article_name'))
最佳答案
不确定为什么需要将逻辑放入一个查询中。似乎是应用 KISS 的完美示例。
为什么不选择具有 1 个参数和普通旧 IF
的函数来提高可读性并使您(也许还有其他开发人员)的生活更轻松?我不认为你正在尝试做的事情有任何优势。除了简洁之外,在这种情况下,我认为这不是最重要的因素。
在 Output.php 模型中:
/**
* Retrieves output of the given type.
*
* @param string $type Type of the output
*
* @return mixed Object or false in case of problems
*/
public static function getOutput($type) {
if (!isset($type) || empty($type) || !in_array($type, ['p', 's'])) {
// Wrong type
return false;
}
if ($type === 'p') {
$baseQuery = Output::join('products', 'products.id', '=', 'outputs.article_id');
$table = 'products';
} else {
$baseQuery = Output::join('services', 'services.id', '=', 'outputs.article_id');
$table = 'services';
}
return $baseQuery
->select('outputs.output_at', $table.'.name as article_name')
->get();
}
然后,在 Controller 中
$output = Output::getOutput('p');
if ($output && count($output)) {
// Do other stuff or pass the data to a view...
}
请记住,这尚未经过测试,并且可能需要与我展示的实现略有不同的实现,但想法仍然清晰。
关于mysql - Laravel 选择加入条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31803733/