hi @rocks3621 i just test my method is working , what kind of relation between product and price ? from your code your product is belongs to a price.
product model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $appends = ['min_price'];
public function price()
{
return $this->belongsTo(Price::class);
}
public function getMinPriceAttribute()
{
// return 100;
return $this->price()->where('type', 1)->exists() ? $this->price->price : null ;
//go to the relationship product list is belong to price so product only has one price
//here we check if product in price table type = 1 if yes , return its price
}
}
price model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Price extends Model
{
use HasFactory;
}
migration file
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->foreignId('price_id')->constrained()->onDelete('cascade');
$table->string('name');
$table->timestamps();
});
}
public function up()
{
Schema::create('prices', function (Blueprint $table) {
$table->id();
$table->decimal('price', 8, 2);
$table->bigInteger('type');
$table->timestamps();
});
}
ur relationship is a product belongs to a price , so inside product table there should be a price_id , price is the parent product is the child
how I retrieve it ?
route::get('min-price', function(){
$product = Product::find(1);
return $product ;
// return dd($product->price->type);
});
my record inside my product table is
INSERT INTO `products` (`id`, `price_id`, `name`, `created_at`, `updated_at`) VALUES
(1, 1, 'product1', '2020-10-12 05:37:47', '2020-10-12 05:37:47'),
(2, 2, 'product2', '2020-10-12 05:37:47', '2020-10-12 05:37:47');
price table
INSERT INTO `prices` (`id`, `price`, `type`, `created_at`, `updated_at`) VALUES
(1, '100.00', 1, '2020-10-12 05:37:18', '2020-10-12 05:37:18'),
(2, '200.00', 2, '2020-10-12 05:37:18', '2020-10-12 05:37:18'),
result I get from the route
{
"id": 1,
"price_id": 1,
"name": "product1",
"created_at": "2020-10-12T13:37:47.000000Z",
"updated_at": "2020-10-12T13:37:47.000000Z",
"min_price": "100.00",
"price": {
"id": 1,
"price": "100.00",
"type": 1,
"created_at": "2020-10-12T13:37:18.000000Z",
"updated_at": "2020-10-12T13:37:18.000000Z"
}
}
does this solve your problem ??