0

I have a 'posts' table and a 'post_images' table. I'm trying to get data from both tables and also join 'users' table to it. it all works but the query returns different objects for each post image.

My AJAX code:

$.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>
                `);

        })
    }
})

The route:

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

The function:

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));
    }

This is what I get in AJAX success:

result

New post has 3 images so it must be one object, not three.

5
  • you are doing a join, if you know how joins work, you should know that if you have multiple images for a post you will have multiple elements with the same post Commented Jun 27, 2019 at 8:08
  • you need a oneToMany relationship or you could manualy convert your array to remove the duplicate posts Commented Jun 27, 2019 at 8:11
  • It appends posts for each image the post has. Commented Jun 27, 2019 at 8:14
  • It is a one to many. One post can have many images. Commented Jun 27, 2019 at 8:14
  • i mean oneToMany laravel relationship Commented Jun 27, 2019 at 8:19

1 Answer 1

1

Create Models and use with() to load relational data.

for table posts => App\Post.php and define relationship like:

<?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');
    }
}

for table post_images => App\PostImage.php Like:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

for table users => App\User.php Like:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Now in your UserController > loadPosts change the code Like:

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.
}

Sign up to request clarification or add additional context in comments.

2 Comments

@GrigoryVolkov let me know if it helps.
Yes it does. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.