Rahadian Wiratama
Rahadian Wiratama

Reputation: 344

Laravel Eloquent Join 2 Tables with Different Name

I want to join 2 tables, t_admin and t_article using eloquent laravel. So this is table t_admin:

id_adm| name   | email
-------------------------
 4    | Arya   | [email protected]  
 7    | Andrea | [email protected]
 12   | Adibah | [email protected]

table t_article:

id_article | id_admin    | title
--------------------------------
 1         |      4      | AAA  
 2         |      12     | BBB
 3         |      7      | CCC

based on that tables, t_admin.id_adm = t_article.id_admin.

This is my model Admin.php

 class Admin extends Model
    {
        protected $fillable = [
            'id_adm','name','email',
        ];
        protected $table = 't_admin';
    }

Article.php

class Article extends Model
{
    protected $fillable = [
        'id_article','id_admin','title',
    ];
    protected $table = 't_article';
}

Upvotes: 1

Views: 5355

Answers (2)

Azraar Azward
Azraar Azward

Reputation: 1624

Add the relationship to the models assuming its one to many

class Admin extends Model
    {
        protected $fillable = [
            'id_adm','name','email',
        ];
        protected $table = 't_admin';


    /**
     * Get the articles for admin.
     */
    public function articles()
    {
        return $this->hasMany('App\Article');
    }

    }



class Article extends Model
{
    protected $fillable = [
        'id_article','id_admin','title',
    ];
    protected $table = 't_article';

    /**
     * Get the user for the article post.
     */
    public function user()
    {
        return $this->belongsTo('App\Admin');

    }
}

You can retrieve them by

$articles = App\Admin::find(1)->articles;

foreach ($articles as $article) {
    //
}

Upvotes: 1

Chukwuemeka Inya
Chukwuemeka Inya

Reputation: 2671

Create a relationship in your Admin Model: Note: I am assuming that an Admin can have many article.

public function articles(){
    return $this->hasMany('App\Article', 'id_admin');
}

Then, whenever you want to get all articles that belong to an Admin, do this:

$adminArticles = Admin::find($adminId)->articles

In a scenario where an Admin can only have one article, do this instead:

public function article(){
    return $this->hasOne('App\Article', 'id_admin');
}

Then, whenever you want to get the article that belongs to an Admin, do this:

$adminArticle = Admin::find($adminId)->article

Read here for more information.

You could also use Laravel's Query Builder to write join queries yourself. In your case, you would do this:

$adminArticles = DB::table('t_admin')
            ->join('t_article', 't_admin.id_adm', '=', 't_article.id_admin')
            ->select('t_admin.*', 't_article.title')
            ->get();

Upvotes: 1

Related Questions