【问题标题】:How to retrieve data from multiple tables in Laravel 5.4如何从 Laravel 5.4 中的多个表中检索数据
【发布时间】:2017-09-04 02:50:49
【问题描述】:

我有两个表,我想从中检索数据并将其传递给我的表。

为此,我创建了 2 个具有一对一关系的模型:

[地址]

class Adress extends Model
{    
     public function KontoKorrent()
     {
         return $this->hasOne(KontoKorrent::class, 'Adresse');
     }
}

[KontoKorrent]

class KontoKorrent extends Model
{
     public function Adresse()
     {
        return $this->belongsTo(Adress::class,'Adresse');
     }
}

我的控制器如下所示:

class AdressesController extends Controller
{
   public function index()
   {
    $adresses = Adress::with('KontoKorrent')->paginate(2);
      return view('welcome', compact('adresses'));

   }
}

当我使用tinker 应用\地址:: 每个adress 都与kontokorrent 有关系。这是有效的。

  App\Adress {#698
         Adresse: "3030",
         Anrede: "Company",
         Name1: "A Company Name",
         LieferStrasse: "Dummystreet",
         KontoKorrent: App\KontoKorrent {#704
           Location: "1",
           Adresse: "3030",
           Kto: "S0043722",

在我看来:

<ul>
  @foreach($adresses as $adress)
    <li>{{ $adress->Name1 }}</li>    //this is working
    <li>{{ $adress->KontoKorrent->Kto }}</li>  //this is NOT working
  @endforeach
</ul>

{{ $adresses->links() }}

关系向我显示错误:

试图获取非对象的属性

我做错了什么?

【问题讨论】:

    标签: php laravel-5.4


    【解决方案1】:

    你得到的错误:

    试图获取非对象的属性

    与某些没有KontoKorrentAdress 模型有关,然后您的$adress-&gt;KontoKorrent 返回null,并且null 不是对象,这就是消息的原因。

    要修复它,你应该做一个if 来检查adress 是否有关系:

    <ul>
      @foreach($adresses as $adress)
        <li>{{ $adress->Name1 }}</li>    //this is working
        <li>
            @if($adress->KontoKorrent)
                {{ $adress->KontoKorrent->Kto }}
            @else
                <!-- Put something here if you want, otherwise remove the @else -->
            @endif
        </li>  //this is NOT working
      @endforeach
    </ul>
    

    这可以缩短为:

    {{ $adress->KontoKorrent ? $adress->KontoKorrent : 'the else content' }}
    

    或在 PHP >= 7.0 中,您可以使用 null coalesce 运算符:

    {{ $adress->KontoKorrent ?? 'the else content' }}
    

    【讨论】:

    • 事实上我有一些空条目。谢谢这解决了我的问题
    猜你喜欢
    • 1970-01-01
    • 2018-01-06
    • 2017-11-13
    • 2018-02-10
    • 2013-05-16
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    相关资源
    最近更新 更多