2017-02-12 124 views
3

我已经在Laravel中设置了我的主应用程序,并为blog(CRUDE)操作设置了WordPress。安装WordPress内public文件夹和配置数据库设置第2数据库在config/database.php Laravel。从laravel查询wordpress数据库

我遇到的麻烦是如何在第二分贝(WordPress)中查询。我想在我的Laravel应用程序的着陆页中显示最新的3篇博客文章。

主要困惑是由于一个帖子在db(WordPress)中有两行,属性为post_status,值为published,第一行为inherit,第二行为inherit。如果精选图像设置为博客文章,则为3行。如果有人能从这个问题中解脱出来,我会非常有帮助。

+1

为什么不使用REST API请求的3个帖子? (wpdomain/wp-json/wp/v2/posts) –

+0

是否所有的文章都有精选图片? –

回答

0

修订版V3

第一件事,第一:你看到inherit是因为该职位已 被修改或添加附件。所以你应该选择 的帖子,其中publish的状态。

MySQL查询得到3最新帖子是:

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模型就像是在 this tutorial提及。我们必须先得到所有的帖子,然后我们必须得到附件 src链接到该帖子。

添加此功能在您的博客帖子型号

Public function getPostById($post_id) 
{ 
    return BlogPost::where('ID', $post_id) 
      ->first(); 
} 

替换此getPosts()方法在博文型号

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/reso urces /视图/测试/ 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 

希望它能帮助!

参考:Accessing WordPress Post through Laravel

+0

我还没有为wordpress的数据库表做任何模型。我需要为他们制作模型吗?如果我应该在他们之间建立什么样的关系? –

+0

我在谷歌周围寻找并找到了一种方法来制作wordpress表格之间的模型和关系。当我查询'$ posts = BlogPost :: orderBy('post_date','desc') - > limit(3) - > get();'我得到3行的属性为'post_status'的表' ('post_status','=','published') - > orderBy('post_date','desc') - > limit(3) - >获得(); ' –

+0

@TanjaForsberg:不,它不是强制性的Modal,但我个人偏好拥有它。并且在查询中有2个问题,我已经更新了我的答案将正确的雄辩查询,请看一看。 –

1

从Laravel docs

使用多个数据库连接

当使用多个连接,您可以访问通过 的连接方法在DB门面每个连接。传递给 连接方法的名称应该对应于您的配置/数据库中列出的连接 之一。PHP配置文件:

$users = DB::connection('foo')->select(...);