Laravel Eloquent associated function name
P粉729198207
P粉729198207 2023-07-23 17:45:15
0
1
410
<p>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: </p> <pre class="brush:php;toolbar:false;"><?php namespace AppModels; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateDatabaseEloquentModel; class Post extends Model { use HasFactory; protected $guarded = ['id']; public function category() { return $this->belongsTo(Category::class); } }</pre> <p>Using this code, the application runs successfully. </p><p>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: </p><p> <code>Post::first()->categories->name</code>, laravel give an error like this <code>Attempt to read property "name" on null in D:BelajarProgramCODINGANLaravelapplicationcoba-laraveleval() 'd code.</code></p> <p>(edited</p> <p>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. </p> <p>)</p> <p>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: </p> <pre class="brush:php;toolbar:false;"><?php namespace AppModels; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateDatabaseEloquentModel; class Category extends Model { use HasFactory; protected $guarded = ['id']; public function posts(){ return $this->hasMany(Post::class); } }</pre> <p>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>
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