Answer the question
In order to leave comments, you need to log in
How to specify table name in result using union?
I implement search in several tables in a DB. Now this is the option:
$pages = Page::select('pages.id', 'pages.title', 'pages.slug')->where('title', 'LIKE', '%' . $string . '%');
$categories = Category::select('categories.id', 'categories.name', 'categories.fullSlug')->where('name', 'LIKE', '%' . $string . '%');
//Еще несколько таких же конструкций
$results = DB::table('posts as post')->select('post.id', 'post.title', 'post.slug')->where('title', 'LIKE', '%' . $string . '%')
$results = $results->union($pages)->union($categories)->get();
#items: array:16 [
0 => {#1279
+"id": 126
+"title": "Категория 2"
+"slug": "category-2"
}
1 => {#1281
+"id": 745
+"title": "Пост в категории"
+"slug": "post-in-category"
}
2 => {#1424
+"id": 801
+"title": "Страница-кат"
+"slug": "page-cat"
}
...
]
if( isset($result->category_name) ) {
//this is categories table
}
#items: array:16 [
0 => {#1279
+"id": 126
+"title": "Категория 2"
+"slug": "category-2",
'table' : 'categories'
}
1 => {#1281
+"id": 745
+"title": "Пост в категории"
+"slug": "post-in-category",
'table' : 'posts'
}
2 => {#1424
+"id": 801
+"title": "Страница-кат"
+"slug": "page-cat",
'table' : 'pages'
}
...
]
Answer the question
In order to leave comments, you need to log in
Union implies that all samples have the same structure and columns, so it takes the names from the first sample.
You can add like this:
select('pages.id', 'pages.title', 'pages.slug', DB::raw('"page" as `type`'))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question