简体   繁体   中英

how to display data from different table using id laravel 8

I have 2 tables, assets and phistories. in table phistories will carry asset_id. i want to display phistories list that under selected asset_id. What i've tried so far in the AssetController:

public function edit(Asset $asset)
    {
        $phistories = (DB::table('phistories')->where('asset_id',$asset)->get()); 
        
        return view('assets.editAsset',[
            'asset' => $asset,
            'phistories' => $phistories
        ]);
    }

this is my view

 @foreach($phistories as $phistory)
      <tr>
        <td>{{$phistory->id}}</td>
        <td><a href="/edit/{{$phistory->id}}/editPhistory"><span>{{$phistory->phistory_name}}</span></a>
        </td>
        <td>{{$phistory->phistory_category}}</td>
        <td>{{$phistory->phistory_pic}}</td>
      </tr>
 @endforeach

My problem is it did not display anything in the view. can anyone check my query is it correct or not or i used a wrong method?

Assuming you have a model named Assets and Phistories, you need to write a many-to-many relationship inside those models. ie

In your Assets model, add this function;

    public function phistories()
    {
        return $this->belongsToMany(Phistories::class);
    }

Once the relationship is defined, you may access the Phistories using the phistories dynamic relationship property from your Assets controller:

use App\Models\Assets;
public function edit(Asset $asset)
    {

        $assets = Assets::with('phistories');
        
        return view('assets.editAsset',['assets' => $assets]);
    }

Use this if you want to be able to access Assets from the Phistories model

In your Phistories model, add this relationship;

    public function Assets()
    {
        return $this->belongsToMany(Assets::class);
    }

Now, Inside your view, you can access the Phistories data like so,

@foreach($assets as $asset)
      <tr>
        <td>{{$asset->id}}</td>
        @foreach($asset->phistories as $phistory)
            <td>
               <a href="/edit/{{$phistory->id}}/editPhistory">
                 <span>{{$phistory->phistory_name}}</span>
               </a>
            </td>
        @endforeach
      </tr>

@endforeach

$phistories = (DB::table('phistories')->where('asset_id',$asset)->get());

to change

$phistories = (DB::table('phistories')->wherein('asset_id',$asset)->get());

if $asset is multiple id's

and second please try first() insted of get()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM