I've got two models:
<?php
namespace blog;
class Posts extends \Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'posts';
public function group() {
return $this->belongsTo('\blog\Authors', 'author_id', 'id');
}
protected function getMylistABC() {
$o_data = Posts::with('Authors')->get();
print $o_data;
}
}
and
<?php
namespace blog;
class Authors extends \Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'authors';
public function users() {
return $this->hasMany('\blog\Posts', 'author_id', 'id');
}
}
But getting to run this:
$o_data = Posts::with('Authors')->get();
Gives me an effect of:
BadMethodCallException Call to undefined method Illuminate\Database\Query\Builder::blog\Authors()
I can't find anything to help sort it out and I think I'm only few clicks away of getting rid of this problem.
$o_data = Posts::with('group')->get();
You have to provide the method name that defines the relationship.
Thank You troydavisson. I'm just catching myself all the time that laravel is simple - and I just forget about simpliest solusions.
Thank You. :)
I'm glad it worked.
To elaborate a bit (and for anyone else that might stumble on this), if you look at your Posts model, there's no way for Eloquent to know what the Authors relationship is without it executing all of your methods (which would be unnecessary and potentially dangerous) since 'Authors' is just given as a string until that method executes and the relationship is resolved and built. So instead, you have to do the eager loading pointing to the code that tells Eloquent which relationship to load.
I am getting this exception BadMethodCallException with message Call to undefine method Illuminate\Database\Query\Builder::assign() My user Class: class User extends Model implements AuthenticatableContract, AuthorizableContract,CanResetPasswordContract { use Authenticatable, Authorizable,CanResetPassword;
protected $hidden = ['password', 'remember_token'];
public function roles(){
return $this->belongsToMany(Role::class);
}
public function hasRole($role){
if (is_string($role)) {
return $this->roles->contains('name',$role);
}
return !!$role->intersect($this->roles)->count();
}
public function assign($role){
if (is_string($role)) {
return $this->roles()->save(
Role::whereName($role)->firstOrFail();
);
}
return $this->roles()->save($role);
}
} My Role Class class Role extends Model { public function permissions(){
return $this->belongsToMany(Permission::class);
}
public function assign(Permission $permission){
return $this->permissions()->save($permission);
}
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community