简体   繁体   中英

Retrieving error on one to many relationship laravel

Been learning laravel for 4 days and im trying to fix this error for 2 hours and i cant still fix it. I can save on one to many relationship but i cant retrieve data i think there something wrong with the relationship. Im trying to retrieve posts on user using this line but im getting not empty results on users but empty result on posts. Same thing happening on categories and posts which is many to many relationship but i cant save on many to many.

$users = User::with('posts')->get();

ANd im getting an error when i use this the error is

Undefined property: Illuminate\\Database\\Eloquent\\Collection::posts()

 $users = User::where('user_id','=','2')->get();

 $posts = $users->posts()->get();

Heres my user Model

use Illuminate\Database\Eloquent\Model;

class User extends Model
{

       protected $primarykey = 'user_id';
        protected $table = 'users';

    public function posts(){
        return $this->hasMany("App\Post");
    }
}

Heres my posts Model

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{

    protected $primarykey = 'id';
        protected $table = 'posts';

    public function post_validation_rules(){
        return [
                'post_title' => 'required|min:5|unique:posts',
                'post_body' => 'required'
            ];
    }

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

     public function categories(){
        return $this->belongsToMany('App\Category', 'category_id', 'category_id');
    }
}

Categories Post

class Category extends Model
{

    protected $primarykey = 'category_id';
        protected $table = 'categories';

    public function posts(){
        return $this->belongsToMany('App\Post', 'post_id', 'id');
    }
}

Database

Posts Table
id
user_id
post_title
post_body
createad_date
updated_date

Users Table
user_id
username
email
pass
createad_date
updated_date

You can only call relations on a single object, not on an entire collection. $users is a collection of User objects.

If you want a single user object, use the first() function to get the first User object that matches.

$user = User::where('user_id','=','2')->first();
$posts = $user->posts;

Update: To get the posts directly in the user object, you need to use the with function:

$user = User::with('posts')->where('user_id','=','2')->first();

Try to declare the field that have the relation between your tables then, for example:

$this->hasMany(App\\Post::class, 'user_id', 'user_id');

Laravel is searching for a field id in User table but it does not exist. so with this way you will tell it that the field you look is user_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM