Hello,
This is a bit of a long post. I am modeling my database after the image on this stackoverflow thread.
http://stackoverflow.com/questions/17711324/database-structure-for-customer-table-having-many-orders-per-customer-and-many
I am mapping that database as follows:
Customer = User (in my app)
Order = Order (in my app)
Product = Song(in my app)
OrderItem = SongOrder(in my app)
I am not sure I am mapping all this out correctly with relationships, and getting the required data seems messy.
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
--SNIP--
public function orders()
{
return $this->hasMany('App\Order');
}
}
class Order extends Model {
public function user()
{
return $this->belongsTo('App\User');
}
public function songorders()
{
return $this->hasMany('App\SongOrder');
}
}
class Song extends Model {
public function artist()
{
return $this->belongsTo('App\Artist');
}
public function songorders()
{
return $this->hasMany('App\SongOrder');
}
}
class SongOrder extends Model {
public function song()
{
return $this->belongsTo('App\Song');
}
public function order()
{
return $this->belongsTo('App\Order');
}
}
For the migrations I do have the foreign key setup for the hasMany relationships for all models like so: (for example).
public function up()
{
Schema::create('orders', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')
->references('id')
->on('users');
$table->string('ordernumber');
$table->timestamps();
});
}
So first off is this the correct way to set all that up according to the image? Secondly this is how I am retrieving the songs the user has ordered and it just feels messy.
$user = \Auth::user();
$orders = $user->orders;
foreach($orders as $order){
$songs = App\SongOrder::where('order_id', $order->id)->get();
echo '<h2>Songs</h2>';
echo $songs;
echo '<hr/>';
}