trait Macroable
{
use \Illuminate\Support\Traits\Macroable {
__call as macroCall;
}
/**
* Get a relationship value from a method.
*
* @param string $key
* @return mixed
* @author Seven Du <shiweidu@outlook.com>
*/
public function getRelationValue($key)
{
$relation = parent::getRelationValue($key);
if (! $relation && static::hasMacro($key)) {
return $this->getRelationshipFromMethod($key);
}
return $relation;
}
/**
* Handle dynamic method calls into the model.
*
* @param string $method
* @param array $parameters
* @return mixed
* @author Seven Du <shiweidu@outlook.com>
*/
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}
return parent::__call($method, $parameters);
}
/**
* Handle dynamic static method calls into the method.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public static function __callStatic($method, $parameters)
{
return parent::__callStatic($method, $parameters);
}
}
只要在要使用的 model 中 use 即可。
使用
有了这个 Trait 那么我们添加到 User 模型中,就可以使用宏能力为其动态添加函数了:
User::macro('questions', function () {
return $this->hasMany(Question::class, 'user_id', 'id');
});
这样,我们可以直接 :
$questions = $user->questions;
拿到用户发布的所有问题了。
以上代码都来自于ThinkSNS Plus,看完整的开发代码可以看仓库:
GitHub: https://github.com/slimkit/thinksns-plus(开源不易,求 Star )
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31448874/viewspace-2143938/ ,如需转载,请注明出处,否则将追究法律责任。