编辑
与此同时,这个问题被访问了几次。只是为了分享我在 stackoverflow 和其他资源的帮助下学到的东西,我不建议使用我要求的技术。更简洁的方法是在控制器中附加一个包含数据库文本的变量:
$txt = Model::find(1);
return view('name', array('text' => $txt->content);
Run Code Online (Sandbox Code Playgroud)
现在您可以像这样访问视图中的文本
{{ $text ?? 'Default' }}
Run Code Online (Sandbox Code Playgroud)
但是,如果您目前也在忙于基本的 oop 和/或 mvc 架构,请继续阅读。也许它有帮助:-)
原问题
我正在尝试输出一些从数据库加载的文本。这是我的设置:
看法:
{{ ContentController::getContent('starttext') }}
Run Code Online (Sandbox Code Playgroud)
控制器:
class ContentController extends BaseController {
public $text = '';
public static function getContent($description)
{
$content = Content::where('description', $description)->get();
$this->text = $content[0]->text;
return $this->text;
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试了各种方法来声明一个类变量并在我的函数中访问它,但我总是得到:
tbh 我想我缺乏一些基本的 oop 知识:-D
我有 3 个模型
1 - 画廊
class Gallery extends \Eloquent {
public function media()
{
return $this->hasMany('Media');
}
}
Run Code Online (Sandbox Code Playgroud)
2- 媒体
class Media extends \Eloquent {
protected $table = 'media';
public function labels()
{
return $this->belongsTo('Label');
}
}
Run Code Online (Sandbox Code Playgroud)
3 - 标签
class Label extends \Eloquent {
public function media()
{
return $this->hasMany('Media');
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试加载包含所有媒体的特定图库。媒体应按相关标签分组并按标签名称列排序。
这不起作用:
$gallery = Gallery::with( [ 'media.labels' => function( $q )
{
$q->orderBy( 'name', 'desc' );
} ] )->where( 'name', 'Gallery1' )->first();
Run Code Online (Sandbox Code Playgroud)
举例说明如何对输出进行排序:
Gallery1
ALabel
Media1 …Run Code Online (Sandbox Code Playgroud)