简体   繁体   中英

display data from database based on other column table laravel 5

I want to display data from spesific column users table, let say uiprv column. and uiprv same as id from provinsi table.

This is User table image:

在此处输入图片说明

and this is provinsi table:

在此处输入图片说明

and now, I've succesfully display data from database but just show "31". 31 is uiprv column from users table, it same thing with id from provinsi table. the question is, how to display data not just 31 , but it can be DKI JAKARTA . like in nama_provinsi at provinsi table .

How should I write code in my controller for this. Thanks in Advance.

Add this in your App/User.php

/**
 * Returns the province of the user
 *
 * @return 
 */
public function province()
{
    // Province is your model related to Provinsi table
    return $this->belongsTo('App\Province');
}

From what you've written,

Relationship between User to Province is Many to one.

Reference - https://laravel.com/docs/5.3/eloquent-relationships

In your User Model add this

    public function province()
    {
        return $this->hasOne('App\Model', 'foreign_key', 'local_key');
    }

And in your controller do this

$data = User::with('province')->get();

You can write a join query to fetch the specific column from table.

eg

$data = DB::table('users')
->join('provinsi','provinsi.id','=','users.uiprv')
->select('users.name_of_column','provinsi.name_of_column')
->get();

Add this in your user model,

     /**
     * Returns the province for the user
     *
     * @return user all details
     */
     public function province()
     {
         return $this->belongsTo('App\Province', 'uiprv', 'id');
     }        

or

     /**
     * Returns the province for the user
     *
     * @return user select details
     */
     public function province()
     {
         return $this->belongsTo('App\Province', 'uiprv', 'id')->select('id', 'nama_provinsi');
     }        

you can add some other fields also in the select.

Try these and reply for this answer.

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