一对多的关系LARAVEL中的Foreach未定义变量

时间:2019-04-26 03:32:08

标签: php laravel

大家好,我想使用一个与很多关系来告知特定用户的指标产品,我的代码似乎正确,但是它有一个不确定的变量,我不知道为什么。我搜索了所有疑难解答,但无法解决。希望你们能帮助我。谢谢。

用户模型

public function indicator(){
    // this is one to many relationship
    return $this->hasMany(Indicator::class);
}

指标型号

class Indicator extends Model
{
    protected $table = 'indicators';
    public $primaryKey = 'id';
    public $timestamp = true;  

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

HomeController

public function index()
{
    $indicators =User::find(1)->indicator;
    return view('pages.index', compact('indicators'));
}

pages.index

@include('layouts.template')

@include('main.carousel')
@include('main.cards')
@include('main.trades')
@include('main.pillars')
@include('main.services')
@include('partials.footer')

@foreach ($indicators as $indicator)
    <h4>{{$indicator->indicator_img}}</h4>
@endforeach

错误

  

“未定义变量:指标(查看:/opt/lampp/htdocs/ecommerceindicator/resources/views/pages/index.blade.php)”

但是如果我使用此App \ User :: find(2)-> Indicator在我的终端上运行php artisan tinker,我可以从表中获取数据

3 个答案:

答案 0 :(得分:0)

在关系中指定外键和本地键。 像这样 return $this->hasOne('App\Phone', 'foreign_key', 'local_key'); 有关更多详细信息,https://laravel.com/docs/5.8/eloquent-relationships#one-to-many-inverse

答案 1 :(得分:0)

这可能对您有用..

$param = @{
    SmtpServer = 'smtp.gmail.com'
    Port = 587
    UseSsl = $true
    Credential  = 'you@gmail.com'
    From = 'you@gmail.com'
    To = 'someone@somewhere.com'
    Subject = 'Sending emails through Gmail with Send-MailMessage'
    Body = "Check out the PowerShellMagazine.com website!"
    Attachments = 'D:\articles.csv'
}

Send-MailMessage @param

答案 2 :(得分:0)

大家好,我已经解决了问题,该问题在web.php中,感谢您回答我的问题

Route::get('/homepage', 'HomeController@index');
Route::get('/homepage', 'PagesController@index');
Route::resource('indicators', 'IndicatorsController');
Route::resource('ebooks', 'EbooksController');
Route::get('/addIndicator', 'PagesController@addindicator');

问题在于网址是相同的,所以我更改了

Route::get('/homepage', 'HomeController@index');
Route::get('/indi', 'PagesController@index1');
Route::resource('indicators', 'IndicatorsController');
Route::resource('ebooks', 'EbooksController');
Route::get('/addIndicator', 'PagesController@addindicator');