dimanche 4 septembre 2016

Laravel hasMany returns 0

I need to create a relationship between a Post and the Likes that it has. I followed the video tutorial on Laracasts exactly besides my class names, but mine didn't work. Laracast Video So I searched for a bit. Most people that have problems with this have a return of null or get an error. When I do it mine returns 0.

Code that returns 0:

>>> $post = App\Post::first();
>>> $post->likes;
=> 0

But if I try this I am able to get the value.

>>> $post->likes()->get();
=> Illuminate\Database\Eloquent\Collection {#656
     all: [
       App\Like {#657
         id: 2,
         post_id: 1,
         user: "robert",
       },
     ],
   }

My Post Class:

namespace App;

use Illuminate\Database\Eloquent\Model;



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

My Like Schema:

Schema::create('likes', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('post_id')->unsigned()->index();
            $table->string('user');
        });

Posts Table Record:

id   => 1
text => Lorem Ipsum
user => Joe

Likes Table Record:

id => 1
post_id => 1
user => robert

What can I do to fix this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire