Laravel查询返回多个对象而不是一个

时间:2019-06-27 08:05:56

标签: jquery ajax laravel

我有一个“帖子”表和一个“ post_images”表。我正在尝试从两个表中获取数据,也将“用户”表加入其中。一切正常,但是查询为每个帖子图像返回不同的对象。

我的AJAX代码:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$.ajax({
    url: '/loadPosts',
    type: 'GET',
    dataType: 'json',
    data: {_token: "{{ csrf_token() }}"},
    success: function(r){


        console.log(r);

        r.forEach((post)=>{

                $('.posts-div').append(` 
                    <div class="card mb-3">
                      <h5 class="card-header">
                      <img src="https://www.stickpng.com/assets/images/585e4bf3cb11b227491c339a.png" style="width: 35px; height: 35px;">
                      ${post.name} ${post.surname}
                      </h5>
                      <div class="card-body">
                        <p class="card-text">${post.text}</p>
                        <img src="images/${post.link}" style="width: 100%;">
                      </div>
                    </div>
                `);

        })
    }
})

路线:

Route::get('/loadPosts','UserController@loadPosts');

功能:

public function loadPosts(){

        $my_id = Auth::user()->id;

        $posts = DB::table('posts')->where('user_id','!=',$my_id)->join('post_images','posts.id','=','post_images.post_id')->join('users','posts.user_id','=','users.id')
        ->select('image','link','name','surname','text')
        ->get()
        ->toArray();

        print_r(json_encode($posts));
    }

这就是我在AJAX中获得成功的原因:

result

新帖子有3张图片,因此它必须是一个对象,而不是三个。

1 个答案:

答案 0 :(得分:2)

创建模型并使用with()加载关系数据。

对于表posts => App\Post.php并定义如下关系:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function images()
    {
        return $this->hasMany('App\PostImage');
    }

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

用于表post_images => App\PostImage.php,例如:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class PostImage extends Model
{
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

用于表users => App\User.php,例如:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}

现在在您的UserController > loadPosts中更改代码,例如:

public function loadPosts(){

    $my_id = Auth::user()->id;

    $posts = App::Post->with("images", "user")
                      ->where('user_id','!=', $my_id)
                      ->get()
                      ->toArray();

    print_r(json_encode($posts)); // you can see the unique posts entries along with `images` and `user` inside it.
}