Laravel:从外键中检索数据

时间:2014-11-20 02:45:20

标签: laravel eloquent

我遇到外键问题,特别是我想使用外键获取表数据,我的代码看起来像。

// Migration foo
public function up()
{
    Schema::create('foo', function(Blueprint $table)
    {
        // Default index laravel uses.
        $table->increments('id');

        $table->integer('bar_id')->unsigned();
        $table->text('fake_date')

        // Default timestamps
        $table->timestamps();

        // Foreign Key
        $table->foreign('bar_id')->references('id')->on('bars')->onDelete('cascade')->onUpdate('cascade');
    });
}

public function down()
{
    Schema::drop('foo');
}

// Migration bar
public function up()
{
    Schema::create('bar', function(Blueprint $table)
    {
        // Default index laravel uses.
        $table->increments('id');
        $table->string('name'); // I want to retrieve this data
    });
}

public function down()
{
    Schema::drop('bar');
}

我的foo模特:

class Record extends \Eloquent {
    protected $table = 'foo';

    public function bar()
    {
        return $this->belongsTo('Bar');
    }
}

我的酒吧模特:

public function foo()
{
    return $this->hasMany('Foo');
}
}

到目前为止,我想打印出“' name'在使用foo的视图中的表格栏内。 我在路径foo里面有一个名为show.blade.php的视图,我试过{{$ foo-> bar() - > name}},我收到语法错误:调用未定义的方法Illuminate \ Database \ Query \ Builder :: patients()

为了澄清我试图在bar中发布值名称的值。所以我有一个

的刀片文件
// views/plays/show.blade.php
<p> {{$foo->bar()->name }} </p>

2 个答案:

答案 0 :(得分:0)

在控制器中传递订单值的地方,

$foos=Foo::with('bar')->where(your_condition)->get();

然后访问刀片中的值

@foreach($foos as $foo)
                       <p>{{ $foo->bar->name }}</p>
 @endforeach

答案 1 :(得分:-2)

找到解决方案,错误的语法,你不需要()在bar之前,发布你只需做的名字{{$ foo-&gt; bar-&gt; name}}

相关问题