search

Home  >  Q&A  >  body text

TP5.1 Implement search function in multi-table related query

Problems with the multi-table association search function:

The code is as follows:

// 实现搜索功能
$productName = Request::param('productName');
$storeName = Request::param('storeName');

if ( !empty($productName) && empty($storeName) ) {
    $map[] = ['p.name', 'like', '%' . $productName . '%'];
} else if ( !empty($storeName) && empty($productName) ) {
    $map[] = ['s.name', 'like', '%' . $storeName . '%'];
} else if ( !empty($productName) && !empty($storeName) ) {
    $map[] = ['p.name', 'like', '%' . $productName . '%'];
    $map[] = ['s.name', 'like', '%' . $storeName . '%'];
}

// 定义分页参数
$limit = isset($_GET['limit']) ? $_GET['limit'] : 10;
$page = isset($_GET['page']) ? $_GET['page'] : 1;

$stockList = StockModel::where($map)
    -> alias('sk')
    -> leftJoin('product p', 'sk.product_id = p.id')
    -> join('store s', 'sk.store_id = s.id')
    -> where('sk.status', 1)
    -> order('sk.product_id', 'desc')
    -> field('sk.*, p.name as product_name, s.name as store_name')
    -> page($page, $limit)
    -> select();

1. In the above code, the search function is wanted to be implemented, but in the $map condition, because the search is through Join joins the fields of the attached table, so use the alias of the attached table. The form of the field, such as: p.name, s.name, there is a problem with this search. In the generated SQL statement, both appended tables are filtered, as follows :

01.jpg

02.jpg

The result is that the attached table is gone, so it is wrong to add aliases to the fields.

2. Change the search conditions to the form of table name.field. In this way, it is no problem to search the fields of the main table, but there is still a problem in searching the appendix table. In the SQL statement generated in this way, the appendix table is retained. , but there is still a problem with the search. The error is as follows:

04.jpg

03.jpg

Can anyone help me look at this? How to do it? ? ?

JackieJackie1623 days ago1900

reply all(4)I'll reply

  • WJ

    WJ2020-06-17 16:40:17

    It seems that what you wrote is to check data in two related tables. Do you use parma to accept two values?

    You can do this, only receive one value $where

    $map[] = ['p.name | s.name', 'like', '%' . $productName . '%'];

    and then use the link query, plus group "gruop", give it a try!

    I don’t know if what I said is right

    reply
    0
  • Jackie

    This doesn't work either, it still prompts: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'p.name' in 'where clause' The generated SQL statement is as follows: SELECT * FROM `sr_stock` WHERE ( `p`.`name` LIKE '%Helen Keller%' OR `s`.`name` LIKE '%Helen Keller%' )

    Jackie · 2020-06-17 20:35:14
    WJ

    Is product the complete table name?

    WJ · 2020-06-18 11:28:59
    Jackie

    No, my table name prefix is: sr_

    Jackie · 2020-06-18 23:50:33
  • Cancelreply