Home > Blockchain >  how to join laravel model collections
how to join laravel model collections

Time:02-03

I am trying to get into models/collections as opposed to straight sql calls in my controllers. I have 2 database tables.

  1. tasks
  2. resources

My Tasks table

taskName resourceId
someTask 1
task2 2

My Resources table

resourceId name
1 abc
2 xyz

in straight sql i would do

 $sel = "SELECT taskName,resources.resourceId,resources.name ";
 $from = "FROM tasks,resources ";
 $where = "WHERE tasks.resourceId=resources.resourceId";

and get

someTask,1,abc
task2,2,xyz

how can I do this using models, collections?

I know you all like code I have tried, but I am not sure to where to even begin. I can do the basic $x = tasks::all() stuff...

**Edit

tasks.php

class tasks extends Model
{
    /**
 * The database connection that should be used by the model.
 *
 * @var string
 */
    protected $table = 'tasks';
    protected $connection = 'mysql';
}

resources.php

class resources extends Model
{

protected $table = 'resources';
protected $connection = 'mysql';
}

CodePudding user response:

class tasks extends Model
{
    /**
     * Get the phone associated with the user.
     */
    public function resource()
    {
        return $this->hasOne(resources::class,''resourceId','resourceId');
    }
}

$tasks =tasks::with('resource')->get();
        
    foreach($tasks as $task)
    {
        echo $task->taskName.' '.$task->resourceId.' '.$task->resource->Name;
    }
  • Related