我有两个彼此无关的查询,第一个查询返回 4 列,而第二个查询仅返回 1 列。
如何关联这两个表中的数据并生成一个统一的结果集?
查询1-
$sql = "SELECT postlist.*
FROM postlist
ORDER BY postlist.id DESC";
查询2-
$sql1 = "SELECT COUNT(commentlist.id) as 'comments',
commentlist.id,
commentlist.name,
commentlist.comment
FROM postlist, commentlist
WHERE postlist.id=commentlist.post_id";
当前查询-
$sql = "SELECT postlist.*,
COUNT(commentlist.id) AS 'comments'
FROM postlist
LEFT JOIN commentlist ON postlist.id=commentlist.post_id
ORDER BY postlist.id DESC";
基本上,我想返回
postlist
中的所有记录,无论commentlist
表是否有任何相关注释。
这是数据库设计:
DROP TABLE IF EXISTS postlist;
CREATE TABLE postlist (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
post VARCHAR(1000) NOT NULL,
name VARCHAR(80) NOT NULL,
title VARCHAR(80) NOT NULL
);
DROP TABLE IF EXISTS commentlist;
CREATE TABLE commentlist (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
post_id INTEGER NOT NULL,
comment VARCHAR(80) NOT NULL,
name VARCHAR(80) NOT NULL
);
我正在开发一个Laravel应用程序,我尝试过使用
array_merge()
,但似乎我遗漏了一个重要的点。
这是一个路由'/'函数:
Route::get('/', function()
{
$items = get_items();
return View::make('posts')->withItems($items);
});
get_item()
:
function get_items()
{
$sql = "select postlist.* from postlist order by postlist.id desc ";
$items = DB::select($sql);
$sql1 = "select count (commentlist.id) as 'comments',commentlist.id,commentlist.name,commentlist.comment from postlist,commentlist where postlist.id=commentlist.post_id";
$items1 = DB::select($sql1);
$items = array_merge($items, $items1);
return $items;
}
我在其中检索记录的 Blade.php 文件。
@if ($items)
<table class="bordered">
<thead>
<tr><th>Icon</th><th>Title</th><th>Post</th><th>Name</th><th>Update Post </th><th>Delete Post </th><th>View Comments</th></tr>
<tbody>
@foreach ($items as $item)
<tr>
<td><img class='photo' src='image/images.png' alt='photo' style="height:25px; width:35px;" ></td>
<td>{{{ $item->title }}} </td>
<td> {{{ $item->post }}} </td>
<td>{{{ $item->name }}}</td>
<td><a href="{{{ url("update_item/$item->id") }}}">Update</a></td>
<td><a href="{{{ url("delete_item_action/$item->id") }}}">Delete</a></td>
<td><a href="{{{ url("comments_item/$item->id") }}}">Comments</a></td>
</tr>
@endforeach
</tbody>
</table>
@else
<p>No items found.</p>
@endif
@stop
get() 会将其转换为 Collection,这比数组强大得多。您可以附加它、迭代它等等。 尽情狂欢吧。希望它应该是您所需要的:http://laravel.com/docs/4.2/eloquent#collections
$items = DB::select($sql)->get();
$items1 = DB::select($sql1)->get();
$items = items->toArray();
$items1 = items1->toArray();
$items = array_merge($items, $items1);