That shouldn't be a problem, AFAIK. There must be something else wrong.
How to correctly name a method in a model?
I'm a beginner. I'm trying to understand the BD relationships . I always learned by experimental modeling the code. This is a my sample model code:
namespace App;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
public function user()
{
return $this-> belongsTo('App\User');
}
public function test()
{
return $this-> belongsTo('App\User');
}
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
public function test2()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
}
I have properly defined fields in the migration files. But when I use Artisan Tinker... i get results, that I do not understand.
Metod user() and test() is the same. Metod categories() and test()2 is the same.
$sample = App\MyModel::find(1);
$sample -> categories() ->get();
That above, gives me correct results. It's OK.
$sample = App\MyModel::find(1);
$sample -> test2() ->get();
That above, gives me correct results. It's OK.
This means that I can freely named the method. That's great! Until then, everything is understandable and clear. Name of method does not matter. Probably in this case, only a code inside the method is crucial.
Now I'm trying to do it with the other couple:
$sample = App\MyModel::find(1);
$sample -> user() ->get();
That above, gives me correct results. It's OK. But when I use this:
$sample = App\MyModel::find(1);
$sample -> test() ->get();
I receive an empty(?) result:
=> Illuminate\Database\Eloquent\Collection {#713
all: [],
}
Why? I don't understand why the method name cannot be any, in this case.
Please or to participate in this conversation.