我在Laravel上安装了我的主要应用程序,并为blog (原油)操作设置了WordPress。将WordPress安装在public
文件夹中,并在config/database.php
中为第二个数据库配置数据库设置。
我遇到的麻烦是如何在第2 db (WordPress)中查询。我想在我的Laravel应用程序的登陆页面上展示最新的3篇博客文章和他们的特色图片。
造成主要混乱的原因是一篇文章在db (WordPress)中有两行,属性为post_status
,值为published
,第一行为published
,第二行为inherit
。如果功能图片设置为博客文章,则设置3行。如果有人能解决这个问题,我会很有帮助的。
发布于 2017-02-12 19:12:53
更新v3
第一件事:您看到
inherit
是因为该帖子已经修改或添加了附件。所以你应该选择那些具有publish
状态的帖子。
获取3篇最新帖子的MySQL查询是:
SELECT
posts.ID AS post_id,
posts.post_title,
posts.post_date
FROM
whrg_posts AS posts
WHERE
posts.post_status = 'publish'
AND posts.post_type = 'post'
ORDER BY
posts.post_date DESC
LIMIT 3;
假设您已经为Postmeta和Postmeta建立了一个模型,如本教程中提到的那样。我们必须首先得到所有的帖子,然后我们必须得到附件src
链接到该帖子。
在BlogPost模型中添加此函数
Public function getPostById($post_id)
{
return BlogPost::where('ID', $post_id)
->first();
}
替换getPosts()
模型中的BlogPost方法
Public function getPosts()
{
return BlogPost::with('postmetas')
->status()
->type()
->orderBy('post_date', 'DESC')
->limit(3)
->get();
}
在您的控制器中,您可以访问它就像
public function anyPostList()
{
$postImages = []; //array to hold the featured image URL in a key value pair
$BlogPost = new BlogPost();
$posts = $BlogPost->getPosts();
foreach ($posts as $post)
{
if (!empty($post->postmetas))
{
foreach ($post->postmetas as $postmeta)
{
//if _thumbnail_id exists then get its guid for src
if ($postmeta->meta_key == '_thumbnail_id' && !empty($postmeta->meta_value)){
$thumbnail_id = $postmeta->meta_value;
$attachment = $BlogPost->getPostById($thumbnail_id);
if(!empty($attachment->guid))
$postImages[$post->ID] = $attachment->guid;
}
}
}
}
$data = [
'posts' => $posts,
'postImages' => $postImages
];
return view('test.post', $data);
}
要在刀片中显示帖子: project_name/resources/views/test/post.blade.php
@foreach($posts as $post)
<h1>{{ $post->post_title }}</h1>
<span>Published on : {{ $post->post_date }}</span>
@if(isset($postImages[$post->ID]))
<img src="{{$postImages[$post->ID]}}" width="200"/>
@endif
<div>
{{ $post->post_content }}
</div>
@endforeach
发布于 2017-02-13 02:08:26
从Laravel 文档。
使用多个数据库连接 使用多个连接时,可以通过DB facade上的连接方法访问每个连接。传递给connection方法的名称应该对应于config/database.php配置文件中列出的连接之一:
$users = DB::connection('foo')->select(...);
https://stackoverflow.com/questions/42191442
复制相似问题