Laravel Eloquent associated function name
P粉729198207
P粉729198207 2023-07-23 17:45:15
0
1
362

I have two tables, namely "posts" and "categories". The relationship between "posts" and "categories" is many-to-one. Therefore, the code in the "Post" class model is as follows:

belongsTo(Category::class); } }

Using this code, the application runs successfully.

The problem is when I try to change the category function name to "categories" and I try to access the post's category name like this:

Post::first()->categories->name, laravel give an error like this Attempt to read property "name" on null in D:BelajarProgramCODINGANLaravelapplicationcoba-laraveleval() 'd code.

(edited

When the Eloquent function name is "category", "Post::first()->category" returns the category of the post. However, when I try to change the function name to "categories" and access it using "Post::first()->categories", it returns null.

)

I tried changing the name of the Eloquent associated function in the category class model to a random name, but I can still access it and Laravel reports no errors. The code of the category class model is as follows:

hasMany(Post::class); } }

Can anyone help me? Why can I change the Eloquent function name in the category class model but not in the posts class model?

P粉729198207
P粉729198207

reply all (1)
P粉330232096

Doing the following should solve the problem:

public function categories() { return $this->belongsTo(Category::class, 'category_id', 'id'); }
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!